基础工具类
该类封装了get和post方法,传入url, header, param 即可食用
package com.zent.dispathching.sevice;
import com.zent.dispathching.bean.HttpClientResult;
import org.apache.http.Header;
import org.apache.http.HttpStatus;
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.*;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.client.utils.URIBuilder;
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;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* @author bigNoseCat
* @date 2018/11/27
*/
public class HttpClientUtils {
// 编码格式。发送编码格式统一用UTF-8
private static final String ENCODING = "UTF-8";
// 设置连接超时时间,单位毫秒。
private static final int CONNECT_TIMEOUT = 6000;
// 请求获取数据的超时时间(即响应时间),单位毫秒。
private static final int SOCKET_TIMEOUT = 6000;
private static RequestConfig requestConfig = null;
static{
RequestConfig.Builder builder = RequestConfig.custom();
builder.setConnectTimeout(CONNECT_TIMEOUT); //设置连接超时时间,单位毫秒
builder.setSocketTimeout(SOCKET_TIMEOUT); //请求获取数据的超时时间(即响应时间),单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
requestConfig = builder.build();
}
/**
* 发送get请求;核心方法
*/
public static HttpClientResult doGet(String url, Map<String, String> headers, Map<String, String> params) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = doGetHandle(url, headers, params);
return getHttpClientResult(httpClient,httpGet,null);
}
/**
* 发送Post请求;核心方法
*/
public static HttpClientResult doPost(String url, Map<String, String> headers, Map<String, String> params) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = doPosthandle(url, headers, params);
return getHttpClientResult(httpClient,httpPost,null);
}
/**
* 发送get请求;不带请求头和请求参数
* @param url 请求地址
* @throws Exception
*/
public static HttpClientResult doGet(String url) throws Exception {
return doGet(url, null, null);
}
/**
* 发送get请求;带请求参数
*
* @param url 请求地址
* @param params 请求参数集合
* @throws Exception
*/
public static HttpClientResult doGet(String url, Map<String, String> params) throws Exception {
return doGet(url, null, params);
}
/**
* 发送post请求;不带请求头和请求参数
*
* @param url 请求地址
* @return
* @throws Exception
*/
public static HttpClientResult doPost(String url) throws Exception {
return doPost(url, null, null);
}
/**
* 发送post请求;带请求参数
*
* @param url 请求地址
* @param params 参数集合
* @return
* @throws Exception
*/
public static HttpClientResult doPost(String url, Map<String, String> params) throws Exception {
return doPost(url, null, params);
}
/**
* GET 请求handle方法
* @param url 请求地址
* @param headers 请求头集合
* @param params 请求参数集合
* @return
* @throws Exception
*/
public static HttpGet doGetHandle(String url, Map<String, String> headers, Map<String, String> params) throws Exception {
// 创建httpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建访问的地址
URIBuilder uriBuilder = new URIBuilder(url);
if (params != null) {
Set<Map.Entry<String, String>> entrySet = params.entrySet();
for (Map.Entry<String, String> entry : entrySet) {
uriBuilder.setParameter(entry.getKey(), entry.getValue());
}
}
// 创建http对象
HttpGet httpGet = new HttpGet(uriBuilder.build());
httpGet.setConfig(requestConfig);
// 设置请求头
packageHeader(headers, httpGet);
return httpGet;
}
/**
* POST handle方法
* @param url 请求地址
* @param headers 请求头集合
* @param params 请求参数集合
* @throws Exception
*/
public static HttpPost doPosthandle(String url, Map<String, String> headers, Map<String, String> params) throws Exception {
// 创建http对象
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(requestConfig);
// 设置请求头
packageHeader(headers, httpPost);
// 封装请求参数
packageParam(params, httpPost);
// 执行请求并获得响应结果
return httpPost;
}
/**
* Description: 封装请求头
* @param params
* @param httpMethod
*/
public static void packageHeader(Map<String, String> params, HttpRequestBase httpMethod) {
// 封装请求头
if (params != null) {
Set<Map.Entry<String, String>> entrySet = params.entrySet();
for (Map.Entry<String, String> entry : entrySet) {
// 设置到请求头到HttpRequestBase对象中
httpMethod.setHeader(entry.getKey(), entry.getValue());
}
}
}
/**
* Description: 封装请求参数
*
* @param params
* @param httpMethod
* @throws UnsupportedEncodingException
*/
public static void packageParam(Map<String, String> params, HttpEntityEnclosingRequestBase httpMethod)
throws UnsupportedEncodingException {
// 封装请求参数
if (params != null) {
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
Set<Map.Entry<String, String>> entrySet = params.entrySet();
for (Map.Entry<String, String> entry : entrySet) {
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
// 设置到请求的http对象中
httpMethod.setEntity(new UrlEncodedFormEntity(nvps, ENCODING));
}
}
/**
*发送请求,处理请求数据
*/
public static HttpClientResult getHttpClientResult(CloseableHttpClient httpClient, HttpRequestBase httpMethod, HttpClientContext httpClientContext) {
CloseableHttpResponse response = null;
try {
response = httpClient.execute(httpMethod,httpClientContext);
if(response == null || response.getStatusLine() == null){
return new HttpClientResult(HttpStatus.SC_INTERNAL_SERVER_ERROR);
}
String content = "";
if (response.getEntity() != null) {
content = EntityUtils.toString(response.getEntity(), ENCODING);
}
Header cookie = response.getFirstHeader("Set-Cookie");
System.out.println( cookie.getName());
System.out.println( cookie.getValue());
return new HttpClientResult(response.getStatusLine().getStatusCode(), content);
}catch (Exception e){
e.printStackTrace();
return new HttpClientResult(HttpStatus.SC_INTERNAL_SERVER_ERROR);
}finally {
try {
release(response,httpClient);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* Description: 释放资源
* @param httpResponse
* @param httpClient
* @throws IOException
*/
public static void release(CloseableHttpResponse httpResponse, CloseableHttpClient httpClient) throws IOException {
// 释放资源
if (httpResponse != null) {
httpResponse.close();
}
if (httpClient != null) {
httpClient.close();
}
}
}
结果返回类
package com.zent.dispathching.bean;
public class HttpClientResult {
private Integer code;
private String content;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public HttpClientResult(Integer code, String content) {
this.code = code;
this.content = content;
}
public HttpClientResult(Integer code) {
this.code = code;
}
@Override
public String toString() {
return "HttpClientResult{" +
"code=" + code +
", content='" + content + '\'' +
'}';
}
}
会话保持类
package com.zent.dispathching.sevice;
import com.zent.dispathching.bean.HttpClientResult;
import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import java.util.Map;
public class HttpSession {
private HttpClientContext httpClientContext;
public HttpSession() {
CookieStore cookieStore = new BasicCookieStore();
httpClientContext = HttpClientContext.create();
httpClientContext.setCookieStore(cookieStore);
}
/**
* 发送get请求;核心方法
*/
public HttpClientResult doGet(String url, Map<String, String> headers, Map<String, String> params) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = HttpClientUtils.doGetHandle(url, headers, params);
return HttpClientUtils.getHttpClientResult(httpClient,httpGet,httpClientContext);
}
/**
* 发送Post请求;核心方法
*/
public HttpClientResult doPost(String url, Map<String, String> headers, Map<String, String> params) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = HttpClientUtils.doPosthandle(url, headers, params);
return HttpClientUtils.getHttpClientResult(httpClient,httpPost,httpClientContext);
}
}
使用方法
保持登录状态请求:
public static void main(String[] args) {
//封装登录参数
Map<String,String> param = new HashMap<String, String>();
param.put("action","login");
param.put("Username","admin");
param.put("Secret","admin");
//这就上面那个类
HttpSession session = new HttpSession();
try {
//登录请求
HttpClientResult httpClientResult = session.doGet("http://172.16.2.3/rawman", null, param);
System.out.println(httpClientResult);
//登陆后要操作的请求
HttpClientResult httpClientResult2 = session.doGet("http://172.16.2.3/rawman?_=1543298733030&action=getExtStatus&Type=none",null,null)
System.out.println(httpClientResult2);
} catch (Exception e) {
e.printStackTrace();
}
}
不保持cookie仅仅发送请求:
public static void main(String[] args) {
//封装登录参数
Map<String,String> param = new HashMap<String, String>();
param.put("action","login");
param.put("Username","admin");
param.put("Secret","admin");
try {
//发送请求
HttpClientResult httpClientResult = HttpClientUtils.doGet("http://172.16.2.3/rawman", param);
System.out.println(httpClientResult);
} catch (Exception e) {
e.printStackTrace();
}
}