import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.*;
public class HttpClientUtils {
/**
* HttpCient Get 请求
* @param url
* @param params 请求参数应该是 name1=value1&name2=value2 的形式。
* @param headers
* @return
* @throws Exception
*/
public static String sendHttpClientGet(String url, String params, Map<String,String> headers) {
HttpClient httpClient;
HttpGet getMethod;
HttpResponse response;
String reponseContent = null;
try {
httpClient = HttpClients.createDefault();
url = url + "?" + params;
getMethod = new HttpGet(url);
if(null == headers){
getMethod.addHeader("Content-type", "text/plain;charset=utf-8");
getMethod.addHeader("accept", "*/*");
getMethod.addHeader("connection", "Keep-Alive");
}else{
//遍历请求头
for(Map.Entry<String,String> entry : headers.entrySet()){
getMethod.addHeader(entry.getKey(),entry.getValue());
}
}
response = httpClient.execute(getMethod);
HttpEntity httpEntity = response.getEntity();
reponseContent = EntityUtils.toString(httpEntity);
EntityUtils.consume(httpEntity);
} catch (Exception e) {
e.printStackTrace();
}
return reponseContent;
}
/**
* HttpClient post 请求 参数为json格式
* @param url
* @param params json 字符串
* @param headers
* @return
*/
public static String sendHttpClientPost(String url,String params,Map<String,String> headers) {
HttpClient httpClient;
HttpPost postMethod;
HttpResponse response;
String reponseContent = null;
try {
httpClient = HttpClients.createDefault();
postMethod = new HttpPost(url);
if(null == headers){
//设置请求头
postMethod.addHeader("Content-type", "text/plain;charset=utf-8");
postMethod.addHeader("accept", "*/*");
postMethod.addHeader("connection", "Keep-Alive");
}else{
//遍历请求头
for(Map.Entry<String,String> entry : headers.entrySet()){
postMethod.addHeader(entry.getKey(),entry.getValue());
}
}
postMethod.setEntity(new StringEntity(params, Charset.forName("UTF-8")));
response = httpClient.execute(postMethod);
System.out.println("response =" +response);
HttpEntity httpEntity = response.getEntity();
reponseContent = EntityUtils.toString(httpEntity);
EntityUtils.consume(httpEntity);
} catch (Exception e) {
e.printStackTrace();
}
return reponseContent;
}
/**
* 模拟表单提交 post 请求
* @param url
* @param param
* @param headers
* @return
*/
public static String sendHttpClientPost(String url, Map<String, String> param,Map<String,String> headers) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// url = url+"?merchantKey="+param.get("merchantKey")+"&merchantTransactionIds="+param.get("merchantTransactionIds");
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
for(Map.Entry<String,String> entry : headers.entrySet()){
httpPost.addHeader(entry.getKey(),entry.getValue());
}
// 创建参数列表
if (param != null) {
List<NameValuePair> paramList = new ArrayList<>();
for (String key : param.keySet()) {
paramList.add(new BasicNameValuePair(key, param.get(key)));
}
// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList,"utf-8");
httpPost.setEntity(entity);
}
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
/**
* 通过 multipart/form-data 请求 上传文件形式
* @param map
* @param url
* @param charset
* @return
*/
public static String postByFormData(Map<String,Object> map, String url,String charset,Map<String,String> headers) {
HttpClient httpClient = HttpClients.createDefault();//从连接池中获取
HttpPost post = new HttpPost(url);
if(null != headers){
for(Map.Entry<String,String> head : headers.entrySet()){
post.setHeader(head.getKey(), head.getValue());//去掉Header
}
}
BufferedReader br = null;
try
{
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
if(map!=null) {
Iterator iter = map.entrySet().iterator();
while(iter.hasNext()){
Map.Entry entry = (Map.Entry) iter.next();
String key = String.valueOf(entry.getKey());
String value = String.valueOf(entry.getValue());
multipartEntityBuilder.addTextBody(key,value);
}
}
HttpEntity httpEntity=multipartEntityBuilder.build();
// 设置请求参数
post.setEntity(httpEntity);
// 发起交易
HttpResponse resp = httpClient.execute(post);
int ret = resp.getStatusLine().getStatusCode();
// 响应分析
HttpEntity entity = resp.getEntity();
br = new BufferedReader(new InputStreamReader(entity.getContent(), charset));
StringBuffer responseString = new StringBuffer();
String result = br.readLine();
while (result != null)
{
responseString.append(result);
result = br.readLine();
}
return responseString.toString();
} catch (Exception e)
{
e.getMessage();
return "";
} finally
{
if (br != null)
{
try
{
br.close();
} catch (IOException e)
{
e.getMessage();
}
}
}
}
/**
* 为了避免需要证书,所以用一个类继承DefaultHttpClient类,忽略校验过程。
* SSLClientUtils
* @param url
* @param jsonstr
* @param charset
* @return
*/
@SuppressWarnings("resource")
public static String sendHttpSSLClientPost(String url,String jsonstr,String charset){
HttpClient httpClient = null;
HttpPost httpPost = null;
String result = null;
try{
httpClient = new SSLClientUtils();
httpPost = new HttpPost(url);
httpPost.addHeader("Content-Type", "application/json");
StringEntity se = new StringEntity(jsonstr);
se.setContentType("text/json");
se.setContentEncoding(new BasicHeader("Content-Type", "application/json"));
httpPost.setEntity(se);
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;
}
public static void main(String[] args) {
String url = "http://localhost/admin.php/user/test/test";
String param = "a=1&b=2&c=3";
Map<String,String> headers = new HashMap<>();
headers.put("Content-type","application/x-www-form-urlencoded");
// headers.put("Content-type","multipart/form-data");
//headers.put("Content-type","application/json");
String s = sendHttpClientPost(url,param,headers);
System.out.println(s);
}
}