HttpClient发送Post请求(二)

时间:2022-01-20 21:10:09

前言

上一篇说的是基于 http 协议发送json、xml形式的报文,本篇介绍键值对方式的参数发送方式


code

package common; 

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

/**
* @author wushucheng
* @version 创建时间:2017年5月13日 上午10:29:50
* 发送http请求
*/
public class HttpUtil {

public static String post(String url, Map<String, String> params){

CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
HttpPost httpPost = new HttpPost(url);

List<NameValuePair> nvp = new ArrayList<NameValuePair>();
for (String key : params.keySet()) {
nvp.add(new BasicNameValuePair(key, params.get(key)));
}

try {
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nvp, "UTF-8");
httpPost.setEntity(urlEncodedFormEntity);
httpClient = HttpClients.createDefault();
response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
return EntityUtils.toString(entity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
if(response != null){
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(httpClient != null){
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

return null;
}

}