下面是详细讲解 Java 通过发送 JSON,POST 请求返回 JSON 数据的攻略:
1. 背景
我们在 Java 中常常需要通过网络请求来获取数据或者发送数据,HTTP 协议是最常见的应用层协议,而使用 HTTP 协议有两种方式: GET 请求和 POST 请求。GET 请求是通过 URL 传递参数,POST 请求是通过 Request Body 传递参数。
JSON(JavaScript Object Notation)是一种轻量级数据交换格式,易于人阅读和编写,同时也易于机器解析和生成。它基于 JavaScript 的一个子集,标准化ECMA-404。
2. 发送 POST 请求并接收 JSON 数据的方法
2.1 Apache HttpClient
Apache HttpClient 是一个基于 Java 语言实现的 HTTP 客户端工具,可以完全模拟客户端发送 HTTP 请求。下面是通过 HttpClient 发送 POST 请求并接收 JSON 数据的示例代码:
import org.apache.http.HttpEntity;
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;
import java.io.IOException;
public class HttpClientExample {
public static void main(String[] args) throws IOException {
String url = "http://example.com/api";
String json = "{\"name\":\"john\",\"age\":30}";
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-type", "application/json");
httpPost.setEntity(new StringEntity(json));
HttpEntity responseEntity = httpClient.execute(httpPost).getEntity();
String response = EntityUtils.toString(responseEntity);
System.out.println(response);
}
}
2.2 URLConnection
URLConnection 是 JDK 自带的与远程服务器进行通信的工具,对 HttpURLConnection 进行封装之后,可以较为方便地进行 HTTP 请求。下面是通过 URLConnection 发送 POST 请求并接收 JSON 数据的示例代码:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class UrlConnectionExample {
public static void main(String[] args) throws IOException {
String url = "http://example.com/api";
String json = "{\"name\":\"john\",\"age\":30}";
URLConnection connection = new URL(url).openConnection();
HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Content-Type", "application/json");
OutputStream outputStream = httpURLConnection.getOutputStream();
outputStream.write(json.getBytes());
outputStream.flush();
outputStream.close();
BufferedReader in = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
String inputLine;
StringBuilder responseBuilder = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
responseBuilder.append(inputLine);
}
in.close();
String response = responseBuilder.toString();
System.out.println(response);
}
}
至此,我们已经讲解了 Java 通过发送 JSON,POST 请求返回 JSON 数据的完整攻略。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:java 通过发送json,post请求,返回json数据的方法 - Python技术站