import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
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.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.client.methods.HttpPut;
import org.apache.http.entity.ByteArrayEntity;
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.CharArrayBuffer;
import org.apache.http.util.EntityUtils;
import com.alibaba.fastjson.JSON;
1、GET请求
参数为Map,拼接在字符串上
public static String get(String url, Map<String, String> map)
{
String result = null;
//创建httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
//设置超时
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(Constant.TIME_OUT)
.setConnectionRequestTimeout(Constant.TIME_OUT)
.setSocketTimeout(Constant.TIME_OUT)
.build();
//拼接参数到url
if (null != map)
{
StringBuffer sb = new StringBuffer(url + "?");
map.forEach((k, v) -> sb.append(k).append("=").append(v).append("&"));
url = sb.toString().substring(0, sb.toString().lastIndexOf("&"));
}
//创建get方式请求对象
HttpGet get = new HttpGet(url);
//设置请求超时时间
get.setConfig(requestConfig);
CloseableHttpResponse response = null;
try
{
//执行请求操作,并拿到结果(同步阻塞)
response = httpClient.execute(get);
if (response != null && response.getStatusLine().getStatusCode() == 200)
{
//获取结果实体
HttpEntity entity = response.getEntity();
//实体转String
result = entityToString(entity);
//返回码
int code = response.getStatusLine().getStatusCode();
}
return result;
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
closeClient(httpClient, response);
}
return null;
}
//实体转String
private static String entityToString(HttpEntity entity)
throws IOException
{
String result = null;
if (entity != null)
{
long lenth = entity.getContentLength();
if (lenth != -1 && lenth < 2048)
{
result = EntityUtils.toString(entity, "UTF-8");
}
else
{
InputStreamReader reader1 = new InputStreamReader(entity.getContent(), "UTF-8");
CharArrayBuffer buffer = new CharArrayBuffer(2048);
char[] tmp = new char[1024];
int l;
while ((l = reader1.read(tmp)) != -1)
{
buffer.append(tmp, 0, l);
}
result = buffer.toString();
if (null != reader1)
reader1.close();
}
}
return result;
}
//关流操作
private static void closeClient(CloseableHttpClient httpClient, CloseableHttpResponse response)
{
try
{
httpClient.close();
if (response != null)
{
response.close();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
2、POST 请求
参数为json字符串,带token验证
public static String post(String url, String token,String jsonString)
{
String result = null;
//创建httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
//设置超时
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(Constant.TIME_OUT)
.setConnectionRequestTimeout(Constant.TIME_OUT)
.setSocketTimeout(Constant.TIME_OUT)
.build();
//创建post方式请求对象
HttpPost post = new HttpPost(url);
//设置请求超时时间
post.setConfig(requestConfig);
CloseableHttpResponse response = null;
try
{
//装填参数
post.setEntity(new ByteArrayEntity(jsonString.getBytes("UTF-8")));
//设置header信息
//指定报文头【Content-type】、【User-Agent】
post.addHeader("Content-Type", "application/json;charset=UTF-8");
//post.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
if (!StringUtils.isBlank(token)) {//设置请求token
post.setHeader("Authorization", "Bearer " + token);
}
//执行请求操作,并拿到结果(同步阻塞)
response = httpClient.execute(post);
if (response != null && response.getStatusLine().getStatusCode() == 200)
{
//获取结果实体
HttpEntity entity = response.getEntity();
//按指定编码转换结果实体为String类型
result = entityToString(entity);
}
return result;
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
closeClient(httpClient, response);
}
return null;
}
参数为JSONObject,带token验证
public static String post(String url, String token,JSONObject jsonObject)
{
String result = null;
//创建httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
//设置超时
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(Constant.TIME_OUT)
.setConnectionRequestTimeout(Constant.TIME_OUT)
.setSocketTimeout(Constant.TIME_OUT)
.build();
//创建post方式请求对象
HttpPost post = new HttpPost(url);
//设置请求超时时间
post.setConfig(requestConfig);
CloseableHttpResponse response = null;
try
{
//装填参数
StringEntity s = new StringEntity(jsonObject.toString(), "UTF-8");
//设置参数到请求对象中
s.setContentEncoding("UTF-8");
s.setContentType("application/json");
post.setEntity(s);
//设置header信息
//指定报文头【Content-type】、【User-Agent】
post.addHeader("Content-Type", "application/json;charset=UTF-8");
//post.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
if (!StringUtils.isBlank(token)) {//设置请求token
post.setHeader("Authorization", "Bearer " + token);
}
//执行请求操作,并拿到结果(同步阻塞)
response = httpClient.execute(post);
if (response != null && response.getStatusLine().getStatusCode() == 200)
{
//获取结果实体
HttpEntity entity = response.getEntity();
//按指定编码转换结果实体为String类型
result = entityToString(entity);
}
return result;
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
closeClient(httpClient, response);
}
return null;
}
参数为Map,不带token验证
public static String post(String url, Map<String, String> map) throws MalformedURLException {
String result = null;
//创建httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
//设置超时
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(Constant.TIME_OUT)
.setConnectionRequestTimeout(Constant.TIME_OUT)
.setSocketTimeout(Constant.TIME_OUT)
.build();
//创建post方式请求对象
URL u = new URL(url);
HttpPost post = new HttpPost(String.valueOf(u));
//HttpPost post = new HttpPost(url);
//设置请求超时时间
post.setConfig(requestConfig);
//转换参数
List<NameValuePair> pairs = new ArrayList<>();
for (Map.Entry<String, String> entry : map.entrySet())
{
pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
CloseableHttpResponse response = null;
try
{
//装填参数
post.setEntity(new UrlEncodedFormEntity(pairs, "UTF-8"));
//根据实际情况定义Header
post.addHeader("Content-Type", "application/x-www-form-urlencoded");
post.addHeader("Authorization","Basic NzljYjEwZjU5N2FhNGJkOGIwYTY0ZTIzZTcyODA5OTg6M0xaY2dGeDFPNUhvV1p0ZkRuekNtZ0hSd0NuRjNrQ2ZYbzY=");
//执行请求操作,并拿到结果(同步阻塞)
response = httpClient.execute(post);
if (response != null && response.getStatusLine().getStatusCode() == 200)
{
//获取结果实体
HttpEntity entity = response.getEntity();
//按指定编码转换结果实体为String类型
result = entityToString(entity);
}
return result;
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
closeClient(httpClient, response);
}
return null;
}