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);
}

二、调用HttpUtil实现

public static String postHeader(String url, List<namevaluepair> params,Map<String,String> headerMap) {
	HttpResponse response = null;
	String data="";
	CloseableHttpClient httpClient = HttpClients.createDefault();
	try {
		HttpPost post = new HttpPost(url);
		
		UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
		post.setEntity(entity);
		for(Entry<String,String> entry:headerMap.entrySet()) {
			post.addHeader(entry.getKey(), entry.getValue());
		}
		
		response =httpClient.execute(post);//
		
		if (response.getStatusLine().getStatusCode() == 200) {
			HttpEntity resEntity = response.getEntity();
			data = EntityUtils.toString(resEntity);
		}
	} catch (Exception e) {
		log.error(e.getMessage(),e);
	} finally {

	}
	return data;

}
public static String doHttpPostJSON(String url, Map headerMap, String json)
		throws ClientProtocolException, IOException {
	HttpClient httpClient = null;
	HttpPost httpPost = null;
	String result = null;

	if (headerMap == null) {
		headerMap = new HashMap();
	}
	httpClient = HttpClientBuilder.create().build();
	RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000).build();
	httpPost = new HttpPost(url);
	httpPost.setConfig(requestConfig);

	// 请求头
	httpPost.setHeader("Accept", ContentTypeJson);

	if (headerMap != null) {
		Iterator iteratorHeader = headerMap.entrySet().iterator();
		while (iteratorHeader.hasNext()) {
			Map.Entry elem = (Map.Entry) iteratorHeader.next();
			httpPost.addHeader(elem.getKey(), elem.getValue());
		}
	}

	httpPost.setHeader("Content-Type", ContentTypeJson);
	// 设置请求参数

	httpPost.setEntity(new StringEntity(json));

	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");
		}
	}

	return result;
}

三、 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群-技术交流

评论: