天天看点

httpclient4.5获取和设置cookie

由于用以前一写版本的代码获取cookie失效后,自己查了下。应该是改过了

下面是代码:

[java]

view plain copy

public static void main(String[] args) {
    CookieStore cookieStore = new BasicCookieStore();
    CloseableHttpClient httpClient = HttpClients.custom()
             .setDefaultCookieStore(cookieStore)
             .build();
     try {

          HttpPost post = new HttpPost("http://www.baiduc.com");
          BasicClientCookie cookie = new BasicClientCookie("name", "zhaoke"); 
          cookie.setVersion(0);  
          cookie.setDomain("/pms/");   //设置范围
          cookie.setPath("/"); 
          cookieStore.addCookie(cookie);
          httpClient.execute(post);//
          List<Cookie> cookies = cookieStore.getCookies();
          for (int i = 0; i < cookies.size(); i++) {
              System.out.println("Local cookie: " + cookies.get(i));
          }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{

        }
    }
           
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

/**
 * 简易http请求
 * @author rubekid
 * @date 2016年10月11日
 */
public class SimpleHttpClient {

    private static CloseableHttpClient httpClient;

    private static CookieStore cookieStore;

    static {
        cookieStore  = new BasicCookieStore();

        // 将CookieStore设置到httpClient中
        httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
    }

    public static String getCookie(String name){
        List<Cookie> cookies =  cookieStore.getCookies();
        for(Cookie cookie : cookies){
            if(cookie.getName().equalsIgnoreCase(name)){
                return cookie.getValue();
            }
        }
        return null;

    }

    /**
     * GET 请求
     * @param url
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static String get(String url) throws ClientProtocolException, IOException {
        HttpGet httpGet = new HttpGet(url);
        HttpResponse httpResponse = httpClient.execute(httpGet);
        return EntityUtils.toString(httpResponse.getEntity());
    }

    /**
     * POST 请求
     * @param url
     * @param params
     * @param headers
     * @return
     * @throws ParseException
     * @throws IOException
     */
    public static String post(String url, Map<String, Object> params, Map<String, String> headers) throws ParseException, IOException{
        HttpPost httpPost = new HttpPost(url);
        UrlEncodedFormEntity postEntity = new UrlEncodedFormEntity(getParam(params), "UTF-8");
        httpPost.setEntity(postEntity);
        if(headers != null){
            addHeaders(httpPost, headers);
        }
        HttpResponse httpResponse = httpClient.execute(httpPost);
        return EntityUtils.toString(httpResponse.getEntity());
    }

    /**
     * 参数
     * @param parameterMap
     * @return
     */
    private static List<NameValuePair> getParam(Map<String, Object> parameterMap) {
        List<NameValuePair> param = new ArrayList<NameValuePair>();
        for(Map.Entry<String, Object> entry : parameterMap.entrySet()){
            param.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue())));
        }
        return param;
    }

    /**
     * 添加头
     * @param httpRequest
     * @param headerMap
     */
    private static void addHeaders(HttpEntityEnclosingRequestBase httpRequest, Map<String, String> headerMap){
        for(Map.Entry<String, String> entry : headerMap.entrySet()){
            httpRequest.addHeader(entry.getKey(), entry.getValue());
        }
    }
}
           

转载自:http://blog.csdn.net/zhao1996ke/article/details/53421961;

http://www.cnblogs.com/rubekid/p/5947819.html