Java对接快递100实时快递单号查询API接口
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public class Kd100Query {
private static final String API_URL = "http://api.kd100.com:9600/api";
private static final String API_KEY = "您的API_KEY"; // 快递100提供的API_KEY
public static void main(String[] args) throws Exception {
String expNo = "快递单号";
String order = "查询方式"; // 如:orderid
String param = "com=kd100&num=" + expNo + "&key=" + API_KEY + "&order=" + order;
String result = sendPost(API_URL, param);
System.out.println(result);
}
private static String sendPost(String urlStr, String param) throws Exception {
URL url = new URL(urlStr);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
try (OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8);
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
out.write(param);
out.flush();
StringBuilder sb = new StringBuilder();
String line;
while ((line = in.readLine()) != null) {
sb.append(line);
}
return sb.toString();
} finally {
connection.disconnect();
}
}
}
这段代码使用了HttpURLConnection类发送POST请求到快递100的API接口,并将查询结果输出。需要替换API_KEY
为您从快递100获取的API\_KEY,以及将expNo
替换为要查询的快递单号。
评论已关闭