HttpClient正确设置Cookie,Header的方法

一、调用方

String url="http://xx.com/v2";
List<namevaluepair> params=new ArrayList<namevaluepair>();
params.add(new BasicNameValuePair("param", "val"));


Map<String,String> headerMap=new HashMap<String,String>();
headerMap.put("headerSign", "xxx41");
headerMap.put("Cookie","token=EA595A8958B81E7B113F9AEE785453AF");



//Cookie设置在Header里
System.out.println("rsp:"+HttpUtils.postHeader(url, params,headerMap));

cookie的另一种设置方法:

CookieStore cookieStore = new BasicCookieStore();

httpClient =HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build();

//请求前可以设置cookieStore

HttpResponse response = httpClient.execute(httpClient);

//请求后,获取服务器设置的Cookie

for(Cookie ck:cookieStore.getCookies()) {
    javax.servlet.http.Cookie nc=new javax.servlet.http.Cookie(ck.getName(),ck.getValue());
    nc.setComment(ck.getComment());
    nc.setDomain(ck.getDomain());
    nc.setMaxAge((int)(ck.getExpiryDate().getTime()-new Date().getTime()));
    nc.setPath(ck.getPath());
    nc.setVersion(ck.getVersion());
    response.addCookie(nc);
}

调用方法:

CookieStore cookieStore=new  BasicCookieStore();
HttpResponse response =HttpUtil.doPost("http://xx/loginByNameAndPwd", headerMap, paramMap, 3000,3000, cookieStore);
for(Cookie ck:cookieStore.getCookies()) {
    javax.servlet.http.Cookie servletCookie=new javax.servlet.http.Cookie(ck.getName(),ck.getValue());
    servletCookie.setDomain(ck.getDomain());
    servletCookie.setPath(ck.getPath());
    servletCookie.setMaxAge((int)(ck.getExpiryDate().getTime()-new Date().getTime()));
    rsp.addCookie(servletCookie);
}

二、调用HttpUtil实现

private static final String ContentType = "application/x-www-form-urlencoded";
private static final String ContentTypeJson = "application/json";
/**
 * HTTP POST请求
 * @param url
 * @param headerMap
 * @param paramMap
 * @return 返回HttpResponse,可操作cookie,判断返回响应码
 */
public static HttpResponse doPost(String url, Map<String, String> headerMap, Map<String, String> paramMap,int connectTimeout,int readTimeout,CookieStore cookieStore) throws Exception{
    HttpClient httpClient = null;
    HttpPost httpPost = null;
   
	httpClient =HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build();
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(readTimeout).setConnectTimeout(connectTimeout).build();
    httpPost = new HttpPost(url);
    httpPost.setConfig(requestConfig);
    
   
    //请求头
    httpPost.addHeader("Content-Type", ContentType);
    if (headerMap != null) {
        Iterator iteratorHeader = headerMap.entrySet().iterator();
        while (iteratorHeader.hasNext()) {
            Map.Entry<String, String> elem = (Map.Entry<String, String>) iteratorHeader.next();
            if(!elem.getKey().equalsIgnoreCase("Content-Length")) {
            	httpPost.addHeader(elem.getKey(), elem.getValue());
            }
        }
    }
    //设置请求参数
    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    if (paramMap != null) {
        Iterator iteratorParam = paramMap.entrySet().iterator();
        while (iteratorParam.hasNext()) {
            Map.Entry<String, String> elem = (Map.Entry<String, String>) iteratorParam.next();
            nameValuePairs.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
        }
    }
    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
    HttpResponse response = httpClient.execute(httpPost);
    return response;   
}

public static String doHttpPost(String url, Map<String, String> headerMap, Map<String, String> paramMap) {
    HttpClient httpClient = null;
    HttpPost httpPost = null;
    String result = null;
    try {
    	httpClient =HttpClientBuilder.create().build();
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000).build();
        httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);
        //希望接收数据格式为json
        httpPost.setHeader("Accept","application/json");
        //请求头,设置成json,接收端请设置成@RequestBody
        //httpPost.setHeader("Content-Type", ContentTypeJson);
        if (headerMap != null) {
            Iterator iteratorHeader = headerMap.entrySet().iterator();
            while (iteratorHeader.hasNext()) {
                Map.Entry<String, String> elem = (Map.Entry<String, String>) iteratorHeader.next();
                if(!elem.getKey().equalsIgnoreCase("Content-Length")) {
                	httpPost.addHeader(elem.getKey(), elem.getValue());
                }
                
            }
        }
        //设置请求参数
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        if (paramMap != null) {
            Iterator iteratorParam = paramMap.entrySet().iterator();
            while (iteratorParam.hasNext()) {
                Map.Entry<String, String> elem = (Map.Entry<String, String>) iteratorParam.next();
                nameValuePairs.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
            }
        }
        
        
        
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs,Charset.forName("utf-8")));
        HttpResponse response = httpClient.execute(httpPost);
        if (response != null && HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
        	
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                result = EntityUtils.toString(resEntity, "UTF-8");
            }
        }
    } catch (Exception ex) {
        logger.error(ex.getMessage(),ex);
    }
    //return JSON.parseObject(result);
    return result;
}

/**
 * HTTP Get请求
 * @param url
 * @param headerMap
 * @param paramMap
 * @return 返回HttpResponse,可操作cookie,判断返回响应码
 */
public static HttpResponse doGet(String url, Map<String, String> headerMap, Map<String, String> paramMap, int connectTimeout, int readTimeout, CookieStore cookieStore) throws Exception{
    HttpClient httpClient = null;
    HttpGet httpGet = null;

    httpClient = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build();
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(readTimeout).setConnectTimeout(connectTimeout).build();
    httpGet = new HttpGet(url);
    httpGet.setConfig(requestConfig);


    //请求头
    httpGet.addHeader("Content-Type", ContentType);
    if (headerMap != null) {
        Iterator iteratorHeader = headerMap.entrySet().iterator();
        while (iteratorHeader.hasNext()) {
            Map.Entry<String, String> elem = (Map.Entry<String, String>) iteratorHeader.next();
            if(!elem.getKey().equalsIgnoreCase("Content-Length")) {
                httpGet.addHeader(elem.getKey(), elem.getValue());
            }
        }
    }
    //设置请求参数
    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    if (paramMap != null) {
        Iterator iteratorParam = paramMap.entrySet().iterator();
        while (iteratorParam.hasNext()) {
            Map.Entry<String, String> elem = (Map.Entry<String, String>) iteratorParam.next();
            nameValuePairs.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
        }
    }
   // httpGet.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
    HttpResponse response = httpClient.execute(httpGet);
    return response;
}

三、 pom依赖

<dependency>
	<groupid>org.apache.httpcomponents</groupid>
	<artifactid>httpclient</artifactid>
	<version>4.5.3</version>
</dependency>
<!-- log -->
<dependency>
	<groupid>log4j</groupid>
	<artifactid>log4j</artifactid>
	<version>1.2.13</version>
</dependency>
<dependency>
	<groupid>org.slf4j</groupid>
	<artifactid>slf4j-log4j12</artifactid>
	<version>1.5.11</version>
</dependency>
<dependency>
	<groupid>org.slf4j</groupid>
	<artifactid>slf4j-api</artifactid>
	<version>1.5.11</version>
</dependency>


Hutool用法:

rspXml = HttpUtil.createPost(apiUrl).body(xml).addHeaders(new HashMap<String,String>(){{
            put("X-EBAY-API-SITEID", "0");
            put("X-EBAY-API-COMPATIBILITY-LEVEL", "986");
            put("X-EBAY-API-CALL-NAME", "GetBidderList");
            put("X-EBAY-API-IAF-TOKEN", tokenVal);
        }}).timeout(5000).execute().body();

文/程忠 浏览次数:0次   2018-08-02 18:10:17

相关阅读

微信扫描-捐赠支持
加入QQ群-技术交流

评论: