在Java中调用POST接口,可以使用以下几种方法:
1. 使用Java原生的HttpURLConnection类发送POST请求:java
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpPostExample {
public static void main(String[] args) {
try {
String url = "http://example.com/api/endpoint";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// 设置请求方法为POST
con.setRequestMethod("POST");
// 设置请求头部信息
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
// 设置POST请求体参数
String postData = "{\"key1\":\"value1\",\"key2\":\"value2\"}";
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(postData);
wr.flush();
wr.close();
// 获取响应结果
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// 打印响应结果
System.out.println(response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
2. 使用第三方库Apache HttpClient发送POST请求:java
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
public class HttpPostExample {
public static void main(String[] args) {
try {
String url = "http://example.com/api/endpoint";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
// 设置请求头部信息
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("User-Agent", "Mozilla/5.0");
// 设置POST请求体参数
String postData = "{\"key1\":\"value1\",\"key2\":\"value2\"}";
StringEntity entity = new StringEntity(postData);
httpPost.setEntity(entity);
// 发送POST请求
HttpResponse response = httpClient.execute(httpPost);
HttpEntity responseEntity = response.getEntity();
// 获取响应结果
String responseString = EntityUtils.toString(responseEntity);
// 打印响应结果
System.out.println(responseString);
} catch (Exception e) {
e.printStackTrace();
}
}
}
上述代码中的url
为POST接口的地址,postData
为POST请求体参数,根据接口的要求进行设置。