httpClient(4.3.1)发送post请求 带cookie(session保持)

package com.*.common;

import java.util.*;

import org.apache.commons.lang.StringUtils;
import org.apache.http.Header;
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.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

public class HttpUtils {

 private static final Logger log = LogManager.getLogger(HttpUtils.class);
 public static String userAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/534.3 (KHTML, like Gecko) Chrome/6.0.472.63 Safari/534.3";
 public static String charset = "UTF-8";
 
 public static void main(String[] args) throws InterruptedException {
  try {
   String url = "http://172.16.15.109:1010/AAA/ai/certAuth.do";
   String cookie = "JSESSIONID=1C070ABFEB05A96FBB1B8F38C3881479;Path=/AAA";
   //设置参数
   Map<String, String> params = new HashMap<String, String>();
   params.put("aaa", "aaa");
   params.put("bbb", "bbbb");
   
   String text = HttpUtils.httpPost1(url, cookie, params);
  } catch (Exception e) {
   log.error(e.getMessage(), e);
  }
 }
 
 /**
  * 描述:httpPost1
  * @param url
  * @param cookie JSESSIONID=1C070ABFEB05A96FBB1B8F38C3881479;Path=/uias
  * @param params
  * @return
  * @throws Exception
  * @CreateOn 2018-5-3  下午4:37:58
  * @author chun_chang
  */
 public static String httpPost1(String url, String cookie, Map<String, String> params) throws Exception {
  String text = "";
  try {
   HttpResponse httpResponse = httpPost2(url, cookie, params);
   String[] arr = getResponseText(httpResponse);
   text = arr[1];
  }catch(Exception e){
   log.error(e.getMessage(), e); 
  }
  return text;
 }
 public static HttpResponse httpPost2(String url, String cookie, Map<String, String> params) throws Exception {
  CloseableHttpClient httpClient = null;
  HttpResponse httpResponse = null;
  try {
   RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build();
   httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
   
   HttpPost httpPost = new HttpPost(url);
   httpPost.addHeader("User-Agent", HttpUtils.userAgent);
   
   if(StringUtils.isNotBlank(cookie)){
    //设置cookie
    //String cookie = "JSESSIONID=1C070ABFEB05A96FBB1B8F38C3881479;Path=/uias";
    httpPost.addHeader(new BasicHeader("Cookie", cookie));
   }
   
   httpPost.setEntity(new UrlEncodedFormEntity(buildParam(params), "UTF-8"));
   httpResponse = httpClient.execute(httpPost);
  } catch(Exception e) {
   log.error(e.getMessage(), e);
  }
  return httpResponse;
 }
 
 public static String[] getResponseText(HttpResponse httpResponse){
  String[] array = { "", "", "" };
  try {
   HttpEntity entity = httpResponse.getEntity();
   Header header = httpResponse.getFirstHeader("Set-Cookie");
   String cookie = "";
   if(null != header){
    cookie = header.getValue();
   }
   int statusCode = httpResponse.getStatusLine().getStatusCode();
   String text = EntityUtils.toString(entity, charset);
   if(statusCode != HttpStatus.SC_OK){
    System.out.println("statusCode=" + statusCode);
    System.out.println("text=" + text);
    System.out.println("cookie=" + cookie);
   }
   return new String[] { statusCode+"", text, cookie };
  } catch(Exception e) {
   log.error(e.getMessage(), e);
  }
  return array;
 }

 
 public static List<NameValuePair> buildParam(Map<String, String> paramsMap) {
  List<NameValuePair> list = new ArrayList<NameValuePair>();
  Iterator<String> iter = paramsMap.keySet().iterator();
  while (iter.hasNext()) {
   String key = iter.next();
   String val = paramsMap.get(key);
   val = null == val ? "" : val;
   list.add(new BasicNameValuePair(key, val));
  }
  return list;
 }
 

}

猜你喜欢

转载自chun521521.iteye.com/blog/2421959