HttpClientUtil工具类post接口调用方式

记录一下常用的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.StringEntity;

import org.apache.http.message.BasicHeader;

import org.apache.http.params.CoreConnectionPNames;

import org.apache.http.util.EntityUtils;

public class HttpClientUtil {

public static String doPost(String url, String jsonstr, String charset) {

HttpClient httpClient = null;

HttpPost httpPost = null;

String result = null;

try {

httpClient = new SSLClient();

httpPost = new HttpPost(url);

httpPost.addHeader("Content-Type", "application/json;charset=utf-8");

httpPost.setHeader("Accept", "application/json");

StringEntity se = new StringEntity(jsonstr, "utf-8");

se.setContentType("text/json");

se.setContentEncoding(new BasicHeader("Content-Type",

"application/json"));

httpPost.setEntity(se);

// 请求超时

httpClient.getParams().setParameter(

CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);

// 读取超时

httpClient.getParams().setParameter(

CoreConnectionPNames.SO_TIMEOUT, 10000);

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;

}

}

使用方式:

Map<String,String> map=new HashMap<String , String>();

map.put("aa", "111");

String url = "http://127.0.0.1:9090/...";

String res = HttpClientUtil.doPost(url, JSONObject.toJSONString(map), "utf-8");

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容