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实现

package net.highersoft.util;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
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.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSONObject;

public class HttpClientUtil {
	private static final String ContentType = "application/x-www-form-urlencoded";
	private static final String ContentTypeJson = "application/json";
	public static final String ContentTypeFormData = "multipart/form-data";
	

	private static final Log logger = LogFactory.getLog(HttpClientUtil.class);





	public static String get(String url, LinkedHashMap<String, String> params) throws IOException {

		String retStr = "";

		CloseableHttpClient httpclient = HttpClients.createDefault();

		try {
			StringBuffer paramsStr = new StringBuffer();
			Set<String> keySet = params.keySet();
			for (String key : keySet) {
				paramsStr.append((-1 == paramsStr.indexOf("?") ? "?" : "&"));
				paramsStr.append(key).append("=").append(params.get(key));
			}

			// logger.info("HTTP GET URL:{}",url + paramsStr);

			HttpGet httpGet = new HttpGet(url + paramsStr);

			CloseableHttpResponse response = httpclient.execute(httpGet);

			// logger.info("HTTP GET StatusLine:{}",response.getStatusLine().toString());

			HttpEntity entity = response.getEntity();

			retStr = EntityUtils.toString(entity, "UTF-8");

			// logger.info("HTTP GET Result:{}", retStr);

			EntityUtils.consume(entity);

		} finally {
			httpclient.close();
		}

		return retStr;
	}

	public static String doHttpPost(String url, Map<String, String> headerMap, Map<String, String> paramMap,
			String paramType) {{
				HttpClient httpClient = null;
				HttpPost httpPost = null;
				String result = null;
				try {
					if (headerMap == null) {
						headerMap = new HashMap<String, String>();
					}
					httpClient = HttpClientBuilder.create().build();
					RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000)
							.build();
					httpPost = new HttpPost(url);
					httpPost.setConfig(requestConfig);

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

					
					Iterator<Map.Entry<String,String>> iteratorHeader = headerMap.entrySet().iterator();
					while (iteratorHeader.hasNext()) {
						Map.Entry<String, String> elem =  iteratorHeader.next();
						httpPost.addHeader(elem.getKey(), elem.getValue());
					}
					

					if (paramType == null || ContentType.equals(paramType)) {
						//如果不传,当成form-data方式

						httpPost.setHeader("Content-Type", ContentType);

						// 设置请求参数
						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()));
							}
						}
						UrlEncodedFormEntity urlEncodedFormEntity=new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8);

						httpPost.setEntity(urlEncodedFormEntity);

					}else if(ContentTypeFormData.equals(paramType)){
						String boundary="--"+ UUID.randomUUID().toString();
						httpPost.setHeader("Content-Type", ContentTypeFormData+";boundary="+boundary);
						MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
						multipartEntityBuilder.setBoundary(boundary);
						for(Map.Entry<String,String> param : paramMap.entrySet()){
							multipartEntityBuilder.addPart(param.getKey(), new StringBody(param.getValue(), org.apache.http.entity.ContentType.MULTIPART_FORM_DATA));
						}
						HttpEntity reqEntity = multipartEntityBuilder.build();
						httpPost.setEntity(reqEntity);
					}


					else if (paramType != null && paramType.equals(ContentTypeJson)) {
						// 设置请求参数
						httpPost.setHeader("Content-Type", ContentTypeJson);
						String json = JSONObject.toJSONString(paramMap);
						if (json != null) {
							StringEntity httpEntity = new StringEntity("JSON: " + json, HTTP.UTF_8);
							httpEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
							httpPost.setEntity(httpEntity);
						}
					}



					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 result;
			}}
	
	public static void main(String args[]) {
		String url="http://xx/xx";
		Map<String,String> headerMap=new HashMap<String,String>();
		headerMap.put("something","1");
		
		
		Map<String,String> paramMap=new HashMap<String,String>();
		paramMap.put("request","{}");
		
		String rst=HttpClientUtil.doHttpPost(url, headerMap, paramMap, ContentTypeFormData);
		System.out.println(rst);
	}
}


这个类增加了form-data类型,可以上传文件。得意

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

评论:
点击刷新

↓ 广告开始-头部带绿为生活 ↓
↑ 广告结束-尾部支持多点击 ↑