1. Overview
1.概述
In this tutorial, we’ll demonstrate how to make a JSON POST request using HttpURLConnection.
在本教程中,我们将演示如何使用JSON POST请求,HttpURLConnection/a>。
2. Building a JSON POST Request With HttpURLConnection
2.用HttpURLConnection建立一个JSON POST请求
2.1. Create a URL Object
2.1.创建一个URL对象
Let’s create a URL object with a target URI string that accepts the JSON data via HTTP POST method:
让我们创建一个带有目标URI字符串的URL对象,通过HTTP POST方法接受JSON数据。
URL url = new URL ("https://reqres.in/api/users");
2.2. Open a Connection
2.2.打开一个连接
From the above URL object, we can invoke the openConnection method to get the HttpURLConnection object.
从上述URL对象中,我们可以调用openConnection方法来获得HttpURLConnection对象。
We can’t instantiate HttpURLConnection directly, as it’s an abstract class:
我们不能直接实例化HttpURLConnection,因为它是一个抽象的类。
HttpURLConnection con = (HttpURLConnection)url.openConnection();
2.3. Set the Request Method
2.3.设置请求方法
To send a POST request, we’ll have to set the request method property to POST:
为了发送一个POST请求,我们必须将请求方法属性设置为POST。
con.setRequestMethod("POST");
2.4. Set the Request Content-Type Header Parameter
2.4.设置请求的Content-Type标头参数
Set the “content-type” request header to “application/json” to send the request content in JSON form. This parameter has to be set to send the request body in JSON format.
将“content-type”请求头设为“application/json”以JSON形式发送请求内容。必须设置这个参数才能以JSON格式发送请求正文。
Failing to do so, the server returns HTTP status code “400-bad request”:
如果不这样做,服务器会返回HTTP状态代码 “400-坏请求”。
con.setRequestProperty("Content-Type", "application/json");
2.5. Set Response Format Type
2.5.设置响应格式类型
Set the “Accept” request header to “application/json” to read the response in the desired format:
将“Accept”请求头设为“application/json”,以便以期望的格式读取响应:。
con.setRequestProperty("Accept", "application/json");
2.6. Ensure the Connection Will Be Used to Send Content
2.6.确保该连接将被用于发送内容
To send request content, let’s enable the URLConnection object’s doOutput property to true.
为了发送请求内容,我们将URLConnection对象的doOutput属性设为true。
Otherwise, we won’t be able to write content to the connection output stream:
否则,我们将无法向连接输出流写入内容。
con.setDoOutput(true);
2.7. Create the Request Body
2.7.创建请求主体
After creating a custom JSON String:
在创建一个自定义的JSON字符串后。
String jsonInputString = "{"name": "Upendra", "job": "Programmer"}";
We would need to write it:
我们将需要写出它。
try(OutputStream os = con.getOutputStream()) {
byte[] input = jsonInputString.getBytes("utf-8");
os.write(input, 0, input.length);
}
2.8. Read the Response From Input Stream
2.8.从输入流读取响应
Get the input stream to read the response content. Remember to use try-with-resources to close the response stream automatically.
获取输入流以读取响应内容。记住要使用try-with-resources来自动关闭响应流。
Read through the whole response content, and print the final response string:
读取整个响应内容,并打印最后的响应字符串。
try(BufferedReader br = new BufferedReader(
new InputStreamReader(con.getInputStream(), "utf-8"))) {
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
System.out.println(response.toString());
}
If the response is in JSON format, use any third-party JSON parsers such as Jackson library, Gson, or org.json to parse the response.
如果响应是JSON格式,请使用任何第三方JSON解析器,如Jackson库、Gson,或org.json来解析响应。
3. Conclusion
3.总结
In this article, we learned how to make a POST request with JSON content body using HttpURLConnection.
在这篇文章中,我们学习了如何使用HttpURLConnection进行带有JSON内容体的POST请求。
As always, the relevant code snippets can be found over on GitHub
一如既往,相关的代码片段可以在GitHub上找到。