httpclient使用head添加cookie

最近在使用接口时候,我使用get请求时,需要携带登录态,所以在get请求的时候我需要在head里面把cookie给加上,添加方式get和post完全不一样

Post方式添加cookie

           httpPost = new HttpPost(url);  	             
	          //添加代理配置 // 设置代理
	            RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
	            //设置参数  
	            List<NameValuePair> list = new ArrayList<NameValuePair>();  
	            Iterator iterator = map.entrySet().iterator();  
	            while(iterator.hasNext()){  
	                Entry<String,String> elem = (Entry<String, String>) iterator.next();  
	                list.add(new BasicNameValuePair(elem.getKey(),elem.getValue())); 
	                System.out.println("请求的参数为:"+elem.getKey()+":"+elem.getValue());
	            }  
	            if(list.size() > 0){  
	                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,"utf-8");  
	                httpPost.setEntity(entity);  
	            }  
	                  
	            //设置头部信息
	            httpPost.setHeader("Referer","http://oms.hqygou.com/order/temp/new");
	            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); 
	            httpPost.setHeader("X-Requested-With","XMLHttpRequest");
	            httpPost.setHeader("Cookies",cookies);

  get请求设置头部信息

	                HttpGet httpGet = new HttpGet(url);
			httpGet.setHeader("Connection","keep-alive");
			httpGet.addHeader(new BasicHeader("Cookie", cookies));

  注意了使用:setHeader如果有这个cookie就会在后面直接添加这个cookie

                            addHeader没有这个cookie就新增这个cookie

原文地址:https://www.cnblogs.com/chongyou/p/7808349.html