共计 2525 个字符,预计需要花费 7 分钟才能阅读完成。
在 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 请求体参数,根据接口的要求进行设置。
丸趣 TV 网 – 提供最优质的资源集合!