Java发送httpPost请求--传消息头,消息体的方法

HttpClient工具类拓展sendPost方法

最近开发中需要调外部厂商提供的API接口,接口文档中定义需要传递一个消息头+消息体。参考httpClient工具类中没有相关方法,所以自己写出来,并和大家分享。

代码来一波

import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Map;
/**
* 
* @param url 接口地址
* @param headers 消息头
* @param data 消息体
* @return
*/
public static String sendPost(String url, Map<String, String> headers, String data) {
	String response = null;
	try {
		CloseableHttpClient httpclient = null;
		CloseableHttpResponse httpresponse = null;
		try {
			httpclient = HttpClients.createDefault();
			HttpPost httppost = new HttpPost(url);
			StringEntity stringentity = new StringEntity(data, ContentType.create("application/json", "UTF-8"));
			httppost.setEntity(stringentity);
			// 循环添加header
			Iterator headerIterator = headers.entrySet().iterator();
			while (headerIterator.hasNext()) {
				Entry<String, String> elem = (Entry<String, String>) headerIterator.next();
				httppost.addHeader(elem.getKey(), elem.getValue());
			}
			//发post请求
			httpresponse = httpclient.execute(httppost);
			//utf-8参数防止中文乱码
			response = EntityUtils.toString(httpresponse.getEntity(), "utf-8");
		} finally {
			if (httpclient != null) {
				httpclient.close();
			}
			if (httpresponse != null) {
				httpresponse.close();
			}
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
	return response;
}
发布了2 篇原创文章 · 获赞 6 · 访问量 210

猜你喜欢

转载自blog.csdn.net/rongyongchao/article/details/105257423
今日推荐