HttpClient工具类拓展sendPost方法
最近开发中需要调外部厂商提供的API接口,接口文档中定义需要传递一个消息头+消息体。参考httpClient工具类中没有相关方法,所以自己写出来,并和大家分享。
代码来一波
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
/**
*
* @param url 接口地址
* @param headers 消息头
* @param data 消息体
* @return
*/
public static String sendPost(String url, Map headers, String data) {
String response = null;
try {
CloseableHttpClient httpclient = null;
CloseableHttpResponse httpresponse = null;
try {
httpclient = ();
HttpPost httppost = new HttpPost(url);
StringEntity stringentity = new StringEntity(data, ("application/json", "UTF-8"));
(stringentity);
// 循环添加header
Iterator headerIterator = ().iterator();
while (()) {
Entry elem = (Entry) ();
((), ());
}
//发post请求
httpresponse = (httppost);
//utf-8参数防止中文乱码
response = ((), "utf-8");
} finally {
if (httpclient != null) {
();
}
if (httpresponse != null) {
();
}
}
} catch (Exception e) {
();
}
return response;
}
———————————————— 版权声明:本文为****博主「rongyongchao」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。 原文链接:/rongyongchao/java/article/details/105257423