java怎么调用post接口

52次阅读
没有评论

共计 2531 个字符,预计需要花费 7 分钟才能阅读完成。

在 Java 中调用 POST 接口,可以使用 Java 内置的 HttpURLConnection 类或者 Apache HttpClient 类。下面分别介绍这两种方法:

  1. 使用 HttpURLConnection 类:
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 {
// 创建 URL 对象
URL url = new URL("http://example.com/api/endpoint");
// 创建 HttpURLConnection 对象
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法为 POST
connection.setRequestMethod("POST");
// 添加请求头
connection.setRequestProperty("Content-Type", "application/json");
// 启用输出流,并指定请求体的内容
connection.setDoOutput(true);
String requestBody = "{\"key1\":\"value1\", \"key2\":\"value2\"}";
DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(requestBody);
outputStream.flush();
outputStream.close();
// 获取响应码
int responseCode = connection.getResponseCode();
// 读取响应内容
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {response.append(line);
}
reader.close();
// 打印响应结果
System.out.println("Response Code:" + responseCode);
System.out.println("Response Body:" + response.toString());
} catch (Exception e) {e.printStackTrace();
}
}
}
  1. 使用 Apache HttpClient 类:
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.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
public class HttpPostExample {public static void main(String[] args) {
try {
// 创建 HttpClient 对象
HttpClient httpClient = HttpClientBuilder.create().build();
// 创建 HttpPost 对象,并设置 URL
HttpPost httpPost = new HttpPost("http://example.com/api/endpoint");
// 设置请求头
httpPost.setHeader("Content-Type", "application/json");
// 设置请求体的内容
String requestBody = "{\"key1\":\"value1\", \"key2\":\"value2\"}";
StringEntity requestEntity = new StringEntity(requestBody);
httpPost.setEntity(requestEntity);
// 发送 POST 请求
HttpResponse response = httpClient.execute(httpPost);
// 获取响应码
int responseCode = response.getStatusLine().getStatusCode();
// 读取响应内容
HttpEntity responseEntity = response.getEntity();
String responseBody = EntityUtils.toString(responseEntity);
// 打印响应结果
System.out.println("Response Code:" + responseCode);
System.out.println("Response Body:" + responseBody);
} catch (Exception e) {e.printStackTrace();
}
}
}

以上代码示例中,假设要调用的接口为 http://example.com/api/endpoint,请求体的内容为 {"key1":"value1", "key2":"value2"},你需要根据实际情况进行修改。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-20发表,共计2531字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)