Java 代码构建 JSON 参数并发送 HTTP POST 请求
本教程将向您展示如何使用 Java 代码构建以下 JSON 参数并发送 HTTP POST 请求到指定的 URL:
{
'header': {
'namespace': 'Leelen.Iot.Device.Query',
'name': 'Query',
'messageId': '1bd5d003-31b9-476f-ad03-71d471922821',
'payLoadVersion': 1
},
'payload': {
'accessToken': 'a1527373-1096-4926-a503-2e56f0c5f64f',
'deviceId': '02073C7AAA39EC2B:1:48:54',
'deviceType': 'aircondition',
'extensions': ''
}
}
请求 URL:'http://iot.leelen.com/ttiot/api/thirdIot/iot-api'
以下代码演示了如何构建 JSON 参数并发送 HTTP POST 请求:
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
public class HttpClientExample {
public static void main(String[] args) {
try {
// 构建 JSON 参数
JSONObject header = new JSONObject();
header.put('namespace', 'Leelen.Iot.Device.Query');
header.put('name', 'Query');
header.put('messageId', '1bd5d003-31b9-476f-ad03-71d471922821');
header.put('payLoadVersion', 1);
JSONObject payload = new JSONObject();
payload.put('accessToken', 'a1527373-1096-4926-a503-2e56f0c5f64f');
payload.put('deviceId', '02073C7AAA39EC2B:1:48:54');
payload.put('deviceType', 'aircondition');
payload.put('extensions', '');
JSONObject json = new JSONObject();
json.put('header', header);
json.put('payload', payload);
// 发送 HTTP POST 请求
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost('http://iot.leelen.com/ttiot/api/thirdIot/iot-api');
StringEntity entity = new StringEntity(json.toString());
entity.setContentType('application/json');
httpPost.setEntity(entity);
CloseableHttpResponse response = httpClient.execute(httpPost);
try {
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
String result = EntityUtils.toString(responseEntity);
System.out.println(result);
}
} finally {
response.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
说明:
- 该代码使用了 Apache HttpClient 库发送 HTTP POST 请求。
- 使用
JSONObject类构建 JSON 参数。 - 使用
StringEntity类将 JSON 对象转换为字符串,并将其设置为 HTTP 请求的实体。 - 使用
EntityUtils.toString()方法从 HTTP 响应中获取结果。
注意:
- 确保您的项目中包含 Apache HttpClient 库的依赖项。
- 将代码中的 URL 和其他参数替换为您实际使用的值。
- 处理 HTTP 响应并根据您的需求进行相应操作。
希望本教程能够帮助您了解如何使用 Java 代码构建 JSON 参数并发送 HTTP POST 请求。
原文地址: https://www.cveoy.top/t/topic/oDMu 著作权归作者所有。请勿转载和采集!