HttpClientUtil工具类post接口调用方式

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HttpClientUtil工具类post接口调用方式相关的知识,希望对你有一定的参考价值。

参考技术A 记录一下常用的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

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");

以上是关于HttpClientUtil工具类post接口调用方式的主要内容,如果未能解决你的问题,请参考以下文章

HttpClientUtil工具类,待更新

httpClientUtil的post请求

Spring-Boot ? ShapeFile文件读写工具类+接口调用

轻松把玩HttpClient之封装HttpClient工具类,携带Cookie的请求

JAVA调用接口获取数据

http请求POST和GET调用接口以及反射动态调用Webservices类