使用httpClient获取请求cookie

Posted 576575478-qq

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用httpClient获取请求cookie相关的知识,希望对你有一定的参考价值。

package mytest;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.HttpGet;
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;

public class Test3 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		 CloseableHttpClient httpClient = null;
		 //创建GET请求
		 HttpGet httpget = new HttpGet("对应请求的URL");
	        String result = null;
	        try {
	            CookieStore cookieStore = new BasicCookieStore();
	            httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
	            httpClient.execute(httpget);
	            String JSESSIONID = null;
	            List<Cookie> cookies = cookieStore.getCookies();
	            for (int i = 0; i < cookies.size(); i++) {
	                if (cookies.get(i).getName().equals("JSESSIONID")) {
	                    JSESSIONID = cookies.get(i).getValue();
	                    System.out.println(JSESSIONID);
	                }
	            }
	        } catch (Exception ex) {
	            ex.printStackTrace();
	        }

	}

}
参考:http://hc.apache.org/httpcomponents-client-ga/httpclient/examples/org/apache/http/examples/client/ClientFormLogin.java

  

以上是关于使用httpClient获取请求cookie的主要内容,如果未能解决你的问题,请参考以下文章

在 .net 4.5 中尝试使用 HttpClient 使 cookie 无法响应

如何使用来自 IHttpClientFactory 的 HttpClient 将 cookie 添加到请求中

JAVA--利用HttpClient模拟浏览器登陆请求获取响应的Cookie

客户端怎么使用httpclient向https服务器发送数据

Httpclient Cookie 问题

轻松把玩HttpClient之封装HttpClient工具类,携带Cookie的请求