在Java中发送请求调用别人的接口,可以使用Java的网络编程库如HttpClient或HttpURLConnection。

使用HttpClient发送POST请求的示例代码如下:

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

public class Main {
    public static void main(String[] args) {
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost("http://iot.leelen.com/ttiot/api/thirdIot/iot-api");

        // 设置请求头
        httpPost.setHeader("Content-Type", "application/json");

        // 设置请求体
        String requestBody = "{\"header\":{\"namespace\":\"Leelen.Iot.Device.Control\",\"name\":\"TurnOn\",\"messageId\":\"1bd5d003-31b9-476f-ad03-71d471XXXXXX\",\"payLoadVersion\":1},\"payload\":{\"accessToken\":\"access token\",\"deviceId\":\"23\",\"deviceType\":\"XXX\",\"attribute\":\"powerstate\",\"value\":\"on\",\"extensions\":{\"extension1\":\"\",\"extension2\":\"\"}}}";
        StringEntity requestEntity = new StringEntity(requestBody, ContentType.APPLICATION_JSON);
        httpPost.setEntity(requestEntity);

        try {
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity responseEntity = httpResponse.getEntity();
            String responseString = EntityUtils.toString(responseEntity);
            System.out.println(responseString);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

以上代码使用了Apache HttpClient库,首先创建一个HttpClient实例,然后创建一个HttpPost实例,设置请求的URL和请求头。接下来设置请求体,即接口的参数。最后执行请求并获取响应。注意要处理异常情况。

java 如何发送请求调用别人接口14 设备控制简要描述:设备控制接口请求URL:httpiotleelencomttiotapithirdIotiot-api请求方式:POSTapplication设备打开{ header namespaceLeelenIotDeviceControl nameTurnOn messageId1bd5d003-31b9-476f

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

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