Java HTTP POST 请求:构建 JSON 参数并获取结果
首先需要引入相关的库:
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
然后按照 JSON 格式构建请求参数:
String url = 'http://example.com/api/query';
String namespace = 'Leelen.Iot.Device.Query';
String name = 'Query';
String messageId = '1bd5d003-31b9-476f-ad03-71d471922821';
int payLoadVersion = 1;
String accessToken = 'a1527373-1096-4926-a503-2e56f0c5f64f';
String deviceId = '02073C7AAA39EC2B:1:48:54';
String deviceType = 'aircondition';
String extensions = '';
JSONObject header = new JSONObject();
header.put('namespace', namespace);
header.put('name', name);
header.put('messageId', messageId);
header.put('payLoadVersion', payLoadVersion);
JSONObject payload = new JSONObject();
payload.put('accessToken', accessToken);
payload.put('deviceId', deviceId);
payload.put('deviceType', deviceType);
payload.put('extensions', extensions);
JSONObject request = new JSONObject();
request.put('header', header);
request.put('payload', payload);
String requestBody = request.toString();
这里使用了 JSON 库 org.json.JSONObject,如果没有安装可以从 Maven 仓库中获取。
然后使用 Apache HttpClient 发送 POST 请求:
HttpClient httpClient = new HttpClient();
HttpMethod method = new PostMethod(url);
method.setRequestEntity(new StringRequestEntity(requestBody, 'application/json', 'UTF-8'));
httpClient.executeMethod(method);
String response = method.getResponseBodyAsString();
最后获取到的响应结果为 response 字符串。
原文地址: https://www.cveoy.top/t/topic/oDK6 著作权归作者所有。请勿转载和采集!