以下是使用CloseableHttpClient向http://localhost:8070端口发送post请求,并传入参数,参数类型为JSONObject的示例代码:

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
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.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import java.io.IOException;

public class HttpClientExample {

    public static void main(String[] args) throws IOException {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost("http://localhost:8070");

        JSONObject json = new JSONObject();
        json.put("key1", "value1");
        json.put("key2", "value2");

        StringEntity entity = new StringEntity(json.toString(), ContentType.APPLICATION_JSON);
        httpPost.setEntity(entity);

        CloseableHttpResponse response = httpclient.execute(httpPost);
        try {
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                String responseString = EntityUtils.toString(responseEntity);
                System.out.println(responseString);
            }
        } finally {
            response.close();
        }
    }
}

在上述代码中,我们首先创建了一个CloseableHttpClient实例,然后构造了一个HttpPost对象,设置了请求的url为http://localhost:8070。

然后,我们创建了一个JSONObject实例,向其中添加了两个属性,key1和key2,分别对应值为value1和value2。

接下来,我们创建了一个StringEntity实例,将JSONObject实例转换成字符串,并设置Content-Type为APPLICATION_JSON。然后,我们将这个StringEntity实例设置为HttpPost的实体。

最后,我们执行HttpPost请求,并获取响应的实体,将其转换为字符串并输出。

需要注意的是,上述代码中的JSONObject是指org.json.JSONObject类,不是Java自带的JSONObject类。如果您需要使用Java自带的JSONObject类,可以将上述代码中的JSONObject替换为org.json.JSONObject。


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

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