Java代码发送post请求

该博客介绍了如何使用Java的HttpClient工具类实现POST请求,详细展示了设置请求头、构建JSON格式请求体及处理响应结果的过程,适用于API接口调用和数据交互场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用Java代码访问对应连接,并发送json格式数据,post请求。

1、首先引用工具类HttpClientUtil

/*
 * 利用HttpClient进行post请求的工具类
 */
public class HttpClientUtil {

    public String doPost(String url, Map<String, String> headerMap, String jsonText, String charset) {
        HttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = null;
        InputStream in = null;
        try {
            httpClient = SSLClientFactory.createSSLClientDefault();
            httpPost = new HttpPost(url);
            // 设置参数
            Iterator<Entry<String, String>> iterator = headerMap.entrySet().iterator();
            Entry<String, String> elem = null;
            while (iterator.hasNext()) {
                elem = iterator.next();
                httpPost.addHeader(elem.getKey(), elem.getValue());
            }
            if (StringUtils.isNotBlank(jsonText)) {
                byte[] bytes = jsonText.getBytes(HTTP.UTF_8);
                ByteArrayEntity se = new ByteArrayEntity(bytes);
                httpPost.setEntity(se);
            }
            HttpResponse response = httpClient.execute(httpPost);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    in=resEntity.getContent();
                    result = EntityUtils.toString(resEntity, charset);
                }
            }
        } catch (Exception ex) {

        }
        finally
        {
            if (in != null){
                try
                {
                    in.close ();
                }
                catch (IOException e)
                {
                    e.printStackTrace ();
                }
            }
        }
        return result;
    }
}

2、获取 访问地址、请求头、json格式的请求体

        //获取接口地址
        String url="http://external.rmcp-zsh.bosafe.com/api/v1/ztexternal/user/change";

        //获取请求头
        Map<String, String> headerMap = new HashMap<String, String>();
        headerMap.put("appId", appId);
        headerMap.put("randomNumber",s);
        headerMap.put("timestamp", strTime);
        headerMap.put("signature", w );
        headerMap.put("Content-Type", "application/json");

        //获取请求体
        JSONObject obj = new JSONObject();
        obj.put("appId", appId);
        //将待同步对象集合转换为json数据
        JSONArray userList = JSONUtil.parseArray(split);
        //设置请求体参数
        obj.put("userList",userList);

3、利用工具类HttpClientUtil 访问 并返回结果

HttpClientUtil httpClientUtil = new HttpClientUtil();
//发送post请求
String results = httpClientUtil.doPost(url, headerMap, obj.toJSONString(), Constants.UTF8);
//返回结果
JSONObject resultJson = JSONObject.parseObject(results);
String status =resultJson.getString("status");

Java发送POST请求,我们可以通过引入Apache HttpClient库来实现。下面是引入依赖的代码: 首先,在pom.xml文件中添加以下依赖项: ```xml <dependencies> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.12</version> </dependency> </dependencies> ``` 接下来,我们可以编写Java代码发送POST请求。以下是一个简单的示例: ```java 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.StringEntity; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; import java.io.IOException; public class Main { public static void main(String[] args) { // 创建HttpClient实例 HttpClient httpClient = HttpClientBuilder.create().build(); // 创建HttpPost请求 HttpPost httpPost = new HttpPost("http://example.com/post-endpoint"); // 设置POST请求的内容 String requestBody = "This is the request body"; StringEntity stringEntity = new StringEntity(requestBody, "utf-8"); httpPost.setEntity(stringEntity); // 发送POST请求并获取响应 try { HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity responseEntity = httpResponse.getEntity(); String responseBody = EntityUtils.toString(responseEntity); // 处理响应 System.out.println("Response status code: " + httpResponse.getStatusLine().getStatusCode()); System.out.println("Response body: " + responseBody); } catch (IOException e) { e.printStackTrace(); } } } ``` 在上述示例代码中,我们创建了一个HttpClient实例,并使用HttpPost对象来设置POST请求的URL和内容。然后,我们使用HttpClient的execute方法发送请求,并通过HttpResponse对象获取响应内容。 注意,这只是一个简单的示例,实际中可能会涉及更多的设置和处理。 希望对你有所帮助!
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值