100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > java post访问工具类(使用post方式请求http接口)

java post访问工具类(使用post方式请求http接口)

时间:2023-11-23 19:57:22

相关推荐

java post访问工具类(使用post方式请求http接口)

1.需要引入的jar包。

使用idea导入com.budjb:http-requests-httpcomponents-client:2.0.2,如下图:

2.工具类HttpUtil.java,代码如下:

package com.util;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.client.methods.HttpPost;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;public class HttpUtil {private static String charset = "utf-8";private static CloseableHttpClient httpClient = HttpClients.createDefault();@SuppressWarnings({"unchecked", "rawtypes"})public static String doPost(String url, String jsonStr) {HttpPost httpPost;String result = null;try {httpPost = new HttpPost(url);// 设置参数httpPost.setHeader("content-Type","application/json;charset=UTF-8");StringEntity entity = new StringEntity(jsonStr);httpPost.setEntity(entity);HttpResponse response = httpClient.execute(httpPost);if (response != null) {HttpEntity resEntity = response.getEntity();if (resEntity != null) {result = EntityUtils.toString(resEntity, charset);}}} catch (Exception ex) {ex.printStackTrace();}return result;}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。