首先需要引入相关的库:

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字符串

如何使用java代码构建下面的json参数并发送http post请求获取结果 header namespace LeelenIotDeviceQuery name Query messageId 1bd5d003-31b9-476f-ad03-71d471922821 payLoadVersion 1 payload

原文地址: https://www.cveoy.top/t/topic/haMs 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录