记录自己写的HttpClientUtils基于HttpClient
上代码
package com.test.common.util;
import com.hangyjx.business.create_template.StringUtil;
import com.lowagie.text.pdf.codec.Base64;
import org.apache.axis.types.Entity;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
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.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.*;
import java.net.URI;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class HttpClientUtil {
/**
* 发送get请求
* @param url
* @param headers
* @return
*/
public static String doGet (String url, Map<String,String> headers){
HttpGet get = new HttpGet();
HttpResponse response = null;
try {
get.setURI(new URI(url));
if (MapUtils.isNotEmpty(headers)) {
for (Map.Entry<String,String> entry: headers.entrySet()) {
get.addHeader(entry.getKey(),entry.getValue());
}
}else {
//没有传headers的默认情况
get.addHeader("Content-Type", "application/json");
}
HttpClient httpClient = HttpClients.createDefault();
response = httpClient.execute(get);
System.out.println("传输数据:url"+url+":"+get);
return EntityUtils.toString(response.getEntity(),"UTF-8");
}catch (Exception e){
System.out.println("请求异常:"+url);
throw new RuntimeException("请求异常:" + url, e);
}finally {
if(response!=null){
EntityUtils.consumeQuietly(response.getEntity());
}
get.releaseConnection();
}
}
/**
* 发送post请求
* @param url
* @param postData
* @param headers
* @return
*/
public static String dopost(String url, String postData , Map<String,String> headers){
HttpPost post = new HttpPost();
HttpResponse response = null;
try {
post.setURI(new URI(url));
if(StringUtils.isNotBlank(postData)){
post.setEntity(new StringEntity(postData,"UTF-8"));
}
if (MapUtils.isNotEmpty(headers)) {
for (Map.Entry<String,String> entry: headers.entrySet()) {
post.addHeader(entry.getKey(),entry.getValue());
}
}else {
//没有传headers的默认情况
post.addHeader("Content-Type", "application/json");
}
HttpClient httpClient = HttpClients.createDefault();
response = httpClient.execute(post);
System.out.println("传输数据:url"+url+":"+postData);
return EntityUtils.toString(response.getEntity(),"UTF-8");
}catch (Exception e){
System.out.println("请求异常:"+url);
throw new RuntimeException("请求异常:" + url, e);
}finally {
if(response!=null){
EntityUtils.consumeQuietly(response.getEntity());
}
post.releaseConnection();
}
}
/**
* 根据url下载文件
* @param url
* @param filepath
* @return
*/
public static String download(String url,String filepath){
try{
HttpClient client = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
HttpResponse response =client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
if (filepath==null){
//获取默认路径
}
File file = new File(filepath);
file.getParentFile().mkdirs();
FileOutputStream fileout = new FileOutputStream(file);
/**
* 根据实际运行效果 设置缓冲区大小
*/
byte[] buffer = new byte[1024];
int ch = 0;
while ((ch = is.read(buffer)) != -1) {
fileout.write(buffer, 0, ch);
}
is.close();
fileout.flush();
fileout.close();
}catch (Exception e){
e.printStackTrace();
}
return null;
}
/**
* 以form表单形式提交数据,发送post请求
* @explain
* 1.请求头:httppost.setHeader("Content-Type","application/x-www-form-urlencoded")
* 2.提交的数据格式:key1=value1&key2=value2...
* @param url 请求地址
* @param paramsMap 具体数据
* @return 服务器返回数据
*/
public static String httpPostWithForm(String url,Map<String, String> paramsMap){
// 用于接收返回的结果
String resultData ="";
try {
HttpPost post = new HttpPost(url);
List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();
// 迭代Map-->取出key,value放到BasicNameValuePair对象中-->添加到list中
for (String key : paramsMap.keySet()) {
pairList.add(new BasicNameValuePair(key, paramsMap.get(key)));
}
UrlEncodedFormEntity uefe = new UrlEncodedFormEntity(pairList, "utf-8");
post.setEntity(uefe);
// 创建一个http客户端
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// 发送post请求
HttpResponse response = httpClient.execute(post);
// 状态码为:200
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
// 返回数据:
resultData = EntityUtils.toString(response.getEntity(),"UTF-8");
}else{
throw new RuntimeException("接口连接失败!");
}
} catch (Exception e) {
throw new RuntimeException("接口连接失败!");
}
return resultData;
}
}