我们经常使用httpClient进行接口间的调用,这里小编给大家展示一个通过httpClient发送带cookie的请求的例子,仅供参考。
首先引入依赖:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.10</version>
</dependency>
接下来上代码:
import cn.wjp.constant.HttpConstant;
import org.apache.http.*;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.CookieSpecs;
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.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.cookie.ClientCookie;
import org.apache.http.impl.client.*;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class HttpUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(HttpUtil.class);
public static final String CHAR_SET="utf-8";
public static RequestConfig defaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build();
/*
*发送普通的带cookie的请求 如果响应有cookie,设置到response
*url:接口地址
*params:请求参数
*requestCookieNames:request中需要发送到接口的cookie的名字
*isSentCookie:是否发送cookie
*isSetCookie:是否将接口返回的cookie放入response中
* setCookieDomain:发送的cookie的domain 这里的值要跟url保持一致 如果接口地址是https://132.108.1.1/xxx/yyy.do 那么该值也要是132.108.1.1 否则发送不了cookie
*/
public static Object normalPost(HttpServletRequest request, HttpServletResponse response,String url,Map<String,String> params,String[] requestCookieNames,boolean isSentCookie,boolean isSetCookie,String setCookieDomain) throws Exception{
if(url==null||url.trim().isEmpty()){
throw new RuntimeException("url为空");
}
CookieStore cookieStore = null;
if(isSentCookie){//将request的cookie放入cookieStore
cookieStore = getCookieStore(request,requestCookieNames,getServerName(url));
}
CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultCookieStore(cookieStore)
.setDefaultRequestConfig(defaultRequestConfig)
.build();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-Type","application/x-www-form-urlencoded");
httpPost.setHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*");
httpPost.setHeader("Cache-Control","max-age=0");
httpPost.setHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36");
httpPost.setConfig(defaultRequestConfig);
httpPost.setEntity(new UrlEncodedFormEntity(getList(params), CHAR_SET));
HttpClientContext context = HttpClientContext.create();
CloseableHttpResponse httpResponse = httpclient.execute(httpPost, context);
// 设置Cookie
if(isSetCookie){//将接口响应的cookie放入response
List<org.apache.http.cookie.Cookie> cookies = context.getCookieStore().getCookies();
setCookiesToResponse(response,cookies,setCookieDomain);
}
int statusCode = httpResponse.getStatusLine().getStatusCode();
String reasonPhrase = httpResponse.getStatusLine().getReasonPhrase();
String result = EntityUtils.toString(httpResponse.getEntity(), CHAR_SET);
LOGGER.info("接口调用地址:"+url+",cookie domain:"+setCookieDomain+",请求参数:"+params);
LOGGER.info("接口调用返回:"+result+","+statusCode+","+reasonPhrase);
httpResponse.close();
httpclient.close();
return 返回你想返回的东西;
}
public static CookieStore getCookieStore(HttpServletRequest request,String[] requestCookieNames,String requestCookieDomain){
if(request==null){
return null;
}
if(requestCookieNames==null||requestCookieNames.length==0){
return null;
}
Cookie[] cookies = request.getCookies();
if(cookies==null||cookies.length==0){
return null;
}
CookieStore cookieStore = new BasicCookieStore();
for(Cookie cookie: cookies){
for(int i=0;i<requestCookieNames.length;i++){
if(cookie.getName().equalsIgnoreCase(requestCookieNames[i])){
org.apache.http.cookie.Cookie cookie_ = new BasicClientCookie(cookie.getName(),cookie.getValue());
((BasicClientCookie)cookie_).setDomain(requestCookieDomain);
((BasicClientCookie)cookie_).setPath("/");
// Set attributes exactly as sent by the server
((BasicClientCookie)cookie_).setAttribute(ClientCookie.PATH_ATTR, "/");
((BasicClientCookie)cookie_).setAttribute(ClientCookie.DOMAIN_ATTR,requestCookieDomain);
cookieStore.addCookie(cookie_);
break;
}
}
}
return cookieStore;
}
private static List<Cookie> setCookiesToResponse(HttpServletResponse response,List<org.apache.http.cookie.Cookie> cookies,String responseCookieDomain){
if(response==null){
return null;
}
if(cookies==null||cookies.size()==0){
return null;
}
if(responseCookieDomain==null||responseCookieDomain.trim().isEmpty()){
LOGGER.error("没有cookie的domian,不进行cookie的设置");
return null;
}
String[] cookieDomains = responseCookieDomain.split(",");
List<Cookie> cookieList = new ArrayList<>();
for(org.apache.http.cookie.Cookie cookie:cookies){
for(String cookieDomian:cookieDomains){
Cookie cookie_ = new Cookie(cookie.getName(),cookie.getValue());
cookie_.setPath("/");
cookie_.setDomain(cookieDomian);
response.addCookie(cookie_);
cookieList.add(cookie_);
}
}
return cookieList;
}
private static List<NameValuePair> getList(Map<String,String> params) {
List<NameValuePair> list = new ArrayList<NameValuePair>();
if(params!=null&¶ms.size()>0){
for (Map.Entry<String,String> entry : params.entrySet()) {
list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
return list;
}
public static String getServerName(String url){
if(url==null||url.trim().isEmpty()){
throw new RuntimeException("url为空");
}
String regexp = "((http[s]?)?(://))?([^:]*)?([^/]*)(/?.*)";
url = url.replaceAll(regexp, "$4");
int index = url.indexOf("/");
if(index>0){
url=url.substring(0,index);
}
return url;
}
}