方式一:

如果想通过 HttpURLConnection 访问网站,网站返回cookie信息,下次再通过HttpURLConnection访问时,把网站返回 cookie信息再返回给该网站。可以使用下面代码。

CookieManager manager = new CookieManager();
CookieHandler.setDefault(manager);

通过这两行代码就可以把网站返回的cookie信息存储起来,下次访问网站的时候,自动帮你把cookie信息带上。

CookieManager还可以设置CookiePolicy。设置如下

CookieManager manager = new CookieManager();
//设置cookie策略,只接受与你对话服务器的cookie,而不接收Internet上其它服务器发送的cookie
manager.setCookiePolicy(CookiePolicy.ACCEPT_ORIGINAL_SERVER);

CookiePolicy 策略机制解析

public interface CookiePolicy {

    public static final CookiePolicy ACCEPT_ALL = new CookiePolicy(){
public boolean shouldAccept(URI uri, HttpCookie cookie) {
return true;
}
}; public static final CookiePolicy ACCEPT_NONE = new CookiePolicy(){
public boolean shouldAccept(URI uri, HttpCookie cookie) {
return false;
}
}; public static final CookiePolicy ACCEPT_ORIGINAL_SERVER = new CookiePolicy(){
public boolean shouldAccept(URI uri, HttpCookie cookie) {
if (uri == null || cookie == null)
return false;
return HttpCookie.domainMatches(cookie.getDomain(), uri.getHost());
}
}; public boolean shouldAccept(URI uri, HttpCookie cookie);
}

从源码中可以看出CookiePolicy 默认提供了3中策略实现机制

  1. CookiePolicy.ACCEPT_ALL;

    从源码中可以发现直接return true。就是接受所有的cookie。
  2. CookiePolicy.ACCEPT_NONE;

    从源码中可以发现直接return false。就是拒绝所有的cookie。
  3. CookiePolicy.ACCEPT_ORIGINAL_SERVER;

    内部调用了HttpCookie.domainMatches的方法。该方法是判断cookie的域和URL的域是否一样,如果一样就return true。只接收域名相同的Cookie

Cookie实现机制

这样每次在调用HttpURLConnection访问网站的时候,通过CookieHandler.getDefault()方法获取CookieManager实例(静态的方法,全局都可用)。

从解析http的响应头中的cookie调用CookieHandler中的put方法存放到CookieStore中。

再次访问网站的时候调用CookieHandler中的get方法获取该uri响应的cookie,并提交到该站点中。

这样开发人员就不需要干预cookie信息,则每次访问网站会自动携带cookie。

代码示例

本例子中使用到了CookieHandler、CookieManager 、CookieStore、 HttpCookie。

public class CookieManagerDemo {

    //打印cookie信息
public static void printCookie(CookieStore cookieStore){
List<HttpCookie> listCookie = cookieStore.getCookies();
listCookie.forEach(httpCookie -> {
System.out.println("--------------------------------------");
System.out.println("class : "+httpCookie.getClass());
System.out.println("comment : "+httpCookie.getComment());
System.out.println("commentURL : "+httpCookie.getCommentURL());
System.out.println("discard : "+httpCookie.getDiscard());
System.out.println("domain : "+httpCookie.getDomain());
System.out.println("maxAge : "+httpCookie.getMaxAge());
System.out.println("name : "+httpCookie.getName());
System.out.println("path : "+httpCookie.getPath());
System.out.println("portlist : "+httpCookie.getPortlist());
System.out.println("secure : "+httpCookie.getSecure());
System.out.println("value : "+httpCookie.getValue());
System.out.println("version : "+httpCookie.getVersion());
System.out.println("httpCookie : "+httpCookie);
});
} public static void requestURL() throws Exception{
URL url = new URL("http://192.168.3.249:9000/webDemo/index.jsp");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
String basic = Base64.getEncoder().encodeToString("infcn:123456".getBytes());
conn.setRequestProperty("Proxy-authorization", "Basic " + basic);
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = null;
while((line=br.readLine())!=null){
System.out.println(line);
}
br.close();
} public static void main(String[] args) throws Exception { CookieManager manager = new CookieManager();
//设置cookie策略,只接受与你对话服务器的cookie,而不接收Internet上其它服务器发送的cookie
manager.setCookiePolicy(CookiePolicy.ACCEPT_ORIGINAL_SERVER);
CookieHandler.setDefault(manager); printCookie(manager.getCookieStore());
//第一次请求
requestURL(); printCookie(manager.getCookieStore());
//第二次请求
requestURL();
} }

方式一:

获取Cookies,多个cookie是以;分隔

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.CookieStore;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.Proxy;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set; public class HttpUtil { public static final String KEY_HEADER_COOKIE="Set-Cookie";
public static final String KEY_REQUEST_COOKIE = "Cookie";
private HttpUtil() { }
public static CookieStore setCookieManager(){
CookieManager manager = new CookieManager();
//设置cookie策略,只接受与你对话服务器的cookie,而不接收Internet上其它服务器发送的cookie
manager.setCookiePolicy(CookiePolicy.ACCEPT_ORIGINAL_SERVER);
CookieHandler.setDefault(manager);
CookieStore cookieStore = manager.getCookieStore();
return cookieStore;
}
public static ResponseResult doGet(String path, Map<String, String> headers, boolean redirect,Proxy proxy) {
HttpURLConnection connection = null;
ResponseResult result = new ResponseResult();
try {
// 1. 得到访问地址的URL
URL url = new URL(new String(path.getBytes(), "UTF-8"));
// 2. 得到网络访问对象java.net.HttpURLConnection
if (proxy != null) {
connection = (HttpURLConnection) url.openConnection(proxy);
} else {
connection = (HttpURLConnection) url.openConnection();
}
/* 3. 设置请求参数(过期时间,输入、输出流、访问方式),以流的形式进行连接 */
// 设置是否向HttpURLConnection输出
connection.setDoOutput(false);
// 设置是否从httpUrlConnection读入
connection.setDoInput(true);
// 设置请求方式
connection.setRequestMethod("GET");
// 设置是否使用缓存
connection.setUseCaches(true);
// 设置此 HttpURLConnection 实例是否应该自动执行 HTTP 重定向
connection.setInstanceFollowRedirects(redirect);
// 设置超时时间
connection.setConnectTimeout(3000);
if (headers != null) {
Set<Entry<String, String>> entrySet = headers.entrySet();
for (Entry<String, String> entry : entrySet) {
connection.setRequestProperty(entry.getKey(), entry.getValue());
}
}
// 连接
connection.connect();
int responseCode = connection.getResponseCode();
result.setResponseCode(responseCode);
String responseMessage = connection.getResponseMessage();
result.setResponseMessage(responseMessage);
List<String> cookies = connection.getHeaderFields().get(KEY_HEADER_COOKIE);
if (cookies != null&&cookies.size()>0) {
StringBuffer sb = new StringBuffer();
for (String string : cookies) {
sb.append(string).append(";");
}
result.setCookies(sb.toString());
}
InputStream inputStream = connection.getInputStream();
StringBuffer sb = new StringBuffer();
// 定义 BufferedReader输入流来读取URL的响应
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
String getLine;
while ((getLine = in.readLine()) != null) {
sb.append(getLine);
}
result.setResponseBody(sb.toString());
inputStream.close();
in.close();
connection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
} public static ResponseResult doPost(String path, Map<String, String> headers, boolean redirect,Proxy proxy,String param){
ResponseResult result = new ResponseResult();
HttpURLConnection connection = null;
try {
// 1. 得到访问地址的URL
URL url = new URL(new String(path.getBytes(), "UTF-8"));
// 2. 得到网络访问对象java.net.HttpURLConnection
if (proxy != null) {
connection = (HttpURLConnection) url.openConnection(proxy);
} else {
connection = (HttpURLConnection) url.openConnection();
}
/* 3. 设置请求参数等 */
// 请求方式
connection.setRequestMethod("POST");
// 超时时间
connection.setConnectTimeout(3000);
// 设置是否输出
connection.setDoOutput(true);
// 设置是否读入
connection.setDoInput(true);
// 设置是否使用缓存
connection.setUseCaches(false);
// 设置此 HttpURLConnection 实例是否应该自动执行 HTTP 重定向
connection.setInstanceFollowRedirects(redirect);
// 设置使用标准编码格式编码参数的名-值对
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
if (headers != null) {
Set<Entry<String, String>> entrySet = headers.entrySet();
for (Entry<String, String> entry : entrySet) {
connection.setRequestProperty(entry.getKey(), entry.getValue());
}
}
// 连接
connection.connect();
/* 4. 处理输入输出 */
// 写入参数到请求中
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
writer.write(new String(param.getBytes(), "UTF-8"));
writer.flush();
writer.close();
int responseCode = connection.getResponseCode();
result.setResponseCode(responseCode);
String responseMessage = connection.getResponseMessage();
result.setResponseMessage(responseMessage);
List<String> cookies = connection.getHeaderFields().get(KEY_HEADER_COOKIE);
if (cookies != null&&cookies.size()>0) {
StringBuffer sb = new StringBuffer();
for (String string : cookies) {
sb.append(string).append(";");
}
result.setCookies(sb.toString());
}
InputStream inputStream = connection.getInputStream();
StringBuffer sb = new StringBuffer();
// 定义 BufferedReader输入流来读取URL的响应
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
String getLine;
while ((getLine = in.readLine()) != null) {
sb.append(getLine);
}
result.setResponseBody(sb.toString());
inputStream.close();
in.close();
connection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
public static ResponseResult doPut(String path, Map<String, String> headers, boolean redirect,Proxy proxy,String param){
ResponseResult result = new ResponseResult();
HttpURLConnection connection = null;
try {
// 1. 得到访问地址的URL
URL url = new URL(new String(path.getBytes(), "UTF-8"));
// 2. 得到网络访问对象java.net.HttpURLConnection
if (proxy != null) {
connection = (HttpURLConnection) url.openConnection(proxy);
} else {
connection = (HttpURLConnection) url.openConnection();
}
/* 3. 设置请求参数等 */
// 请求方式
connection.setRequestMethod("PUT");
// 超时时间
connection.setConnectTimeout(3000);
// 设置是否输出
connection.setDoOutput(true);
// 设置是否读入
connection.setDoInput(true);
// 设置是否使用缓存
connection.setUseCaches(false);
// 设置此 HttpURLConnection 实例是否应该自动执行 HTTP 重定向
connection.setInstanceFollowRedirects(redirect);
// 设置使用标准编码格式编码参数的名-值对
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
if (headers != null) {
Set<Entry<String, String>> entrySet = headers.entrySet();
for (Entry<String, String> entry : entrySet) {
connection.setRequestProperty(entry.getKey(), entry.getValue());
}
}
// 连接
connection.connect();
/* 4. 处理输入输出 */
// 写入参数到请求中
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
writer.write(new String(param.getBytes(), "UTF-8"));
writer.flush();
writer.close();
int responseCode = connection.getResponseCode();
result.setResponseCode(responseCode);
String responseMessage = connection.getResponseMessage();
result.setResponseMessage(responseMessage);
List<String> cookies = connection.getHeaderFields().get(KEY_HEADER_COOKIE);
if (cookies != null&&cookies.size()>0) {
StringBuffer sb = new StringBuffer();
for (String string : cookies) {
sb.append(string).append(";");
}
result.setCookies(sb.toString());
}
InputStream inputStream = connection.getInputStream();
StringBuffer sb = new StringBuffer();
// 定义 BufferedReader输入流来读取URL的响应
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
String getLine;
while ((getLine = in.readLine()) != null) {
sb.append(getLine);
}
result.setResponseBody(sb.toString());
inputStream.close();
in.close();
connection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
public static ResponseResult doDelete(String path, Map<String, String> headers, boolean redirect,Proxy proxy) {
HttpURLConnection connection = null;
ResponseResult result = new ResponseResult();
try {
// 1. 得到访问地址的URL
URL url = new URL(new String(path.getBytes(), "UTF-8"));
// 2. 得到网络访问对象java.net.HttpURLConnection
if (proxy != null) {
connection = (HttpURLConnection) url.openConnection(proxy);
} else {
connection = (HttpURLConnection) url.openConnection();
}
/* 3. 设置请求参数(过期时间,输入、输出流、访问方式),以流的形式进行连接 */
// 设置是否向HttpURLConnection输出
connection.setDoOutput(false);
// 设置是否从httpUrlConnection读入
connection.setDoInput(true);
// 设置请求方式
connection.setRequestMethod("DELETE");
// 设置是否使用缓存
connection.setUseCaches(true);
// 设置此 HttpURLConnection 实例是否应该自动执行 HTTP 重定向
connection.setInstanceFollowRedirects(redirect);
// 设置超时时间
connection.setConnectTimeout(3000);
if (headers != null) {
Set<Entry<String, String>> entrySet = headers.entrySet();
for (Entry<String, String> entry : entrySet) {
connection.setRequestProperty(entry.getKey(), entry.getValue());
}
}
// 连接
connection.connect();
int responseCode = connection.getResponseCode();
result.setResponseCode(responseCode);
String responseMessage = connection.getResponseMessage();
result.setResponseMessage(responseMessage);
List<String> cookies = connection.getHeaderFields().get(KEY_HEADER_COOKIE);
if (cookies != null&&cookies.size()>0) {
StringBuffer sb = new StringBuffer();
for (String string : cookies) {
sb.append(string).append(";");
}
result.setCookies(sb.toString());
}
InputStream inputStream = connection.getInputStream();
StringBuffer sb = new StringBuffer();
// 定义 BufferedReader输入流来读取URL的响应
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
String getLine;
while ((getLine = in.readLine()) != null) {
sb.append(getLine);
}
result.setResponseBody(sb.toString());
inputStream.close();
in.close();
connection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
} class ResponseResult{ private Integer responseCode; private String responseMessage; private String responseBody; private String cookies; public Integer getResponseCode() {
return responseCode;
} public void setResponseCode(Integer responseCode) {
this.responseCode = responseCode;
} public String getResponseMessage() {
return responseMessage;
} public void setResponseMessage(String responseMessage) {
this.responseMessage = responseMessage;
} public String getResponseBody() {
return responseBody;
} public void setResponseBody(String responseBody) {
this.responseBody = responseBody;
} public String getCookies() {
return cookies;
} public void setCookies(String cookies) {
this.cookies = cookies;
}
}

HttpURLConnection 中Cookie 使用的更多相关文章

  1. Http中cookie的使用以及用CookieManager管理cookie

    前段时间项目需要做个接口,接口需要先登录才能进行下一步操作,这里就需要把登录的信息携带下去,进行下一步操作.网上查了很多资料,有很多种方法.下面就介绍较常用 的. 第一种方式: 通过获取头信息的方式获 ...

  2. JavaScript中Cookie的用法

    Javascript中Cookie主要存储于客户端的计算机中,用于存放已访问的站点信息,Cookie最大约为4k.以下实例主要用于页面在刷新时保存数据,具体的用法如下所示: <html> ...

  3. Python中Cookie的处理(一)Cookie库

    Cookie用于服务器实现会话,用户登录及相关功能时进行状态管理.要在用户浏览器上安装cookie,HTTP服务器向HTTP响应添加类似以下内容的HTTP报头: Set-Cookie:session= ...

  4. 使用OKHttp模拟登陆知乎,兼谈OKHttp中Cookie的使用!

    本文主要是想和大家探讨技术,让大家学会Cookie的使用,切勿做违法之事! 很多Android初学者在刚开始学习的时候,或多或少都想自己搞个应用出来,把自己学的十八般武艺全都用在这个APP上,其实这个 ...

  5. HttpURLConnection中使用代理(Proxy)及其验证(Authentication)

    HttpURLConnection中使用代理(Proxy)及其验证(Authentication) 使用Java的HttpURLConnection类可以实现HttpClient的功能,而不需要依赖任 ...

  6. php中cookie实现二级域名可访问操作的方法

    本文实例讲述了php中cookie实现二级域名可访问操作的方法.分享给大家供大家参考.具体方法如下: cookie在一些应用中很常用,假设我有一个多级域名要求可以同时访问主域名绑定的cookie,下面 ...

  7. Laravel5中Cookie的使用

    今天在Laravel框架中使用Cookie的时候,碰到了点问题,自己被迷糊折腾了半多小时.期间研究了Cookie的实现类,也在网站找了许多的资料,包括问答.发现并没有解决问题.网上的答案都是互相抄袭, ...

  8. lr 中cookie的解释与用法

    Loadrunner 中 cookie 解释与用法loadrunner 中与 cookie 处理相关的常用函数如下: web_add_cookie(): 添加新的 cookie 或者修改已经存在的 c ...

  9. 【转】彻底搞清C#中cookie的内容

    http://blog.163.com/sea_haitao/blog/static/77562162012027111212610/ 花了2天时间,彻底搞清C#中cookie的内容,搞清以下内容将让 ...

随机推荐

  1. SFC style CSS variable injection

    摘要 在单文件组件样式中支持使用组件状态驱动的 CSS 变量( CSS 自定义属性). 基础示例 <template> <div class="text"> ...

  2. 【LeetCode】1248. 统计「优美子数组」

    1248. 统计「优美子数组」 知识点:数组:前缀和: 题目描述 给你一个整数数组 nums 和一个整数 k. 如果某个 连续 子数组中恰好有 k 个奇数数字,我们就认为这个子数组是「优美子数组」. ...

  3. VirtualBox 修改Android x86虚拟机的分辨率

    首先说明一下,本人使用的是Windows下的VirtualBox,android x86使用的是9.0-r2版本 一.查看virtualbox中已有的分辨率 启动虚拟机后,连续按两次E键,进入下面页面 ...

  4. PAT甲级:1025 PAT Ranking (25分)

    PAT甲级:1025 PAT Ranking (25分) 题干 Programming Ability Test (PAT) is organized by the College of Comput ...

  5. Leetcode:1008. 先序遍历构造二叉树

    Leetcode:1008. 先序遍历构造二叉树 Leetcode:1008. 先序遍历构造二叉树 思路 既然给了一个遍历结果让我们建树,那就是要需要前序中序建树咯~ 题目给的树是一颗BST树,说明中 ...

  6. windows系统下 PHP怎么安装redis扩展

    在windows系统下安装redis就不赘述了,基本上就是下一步,下一步. 然后通过通过命令行启动服务. 我是在xamp 3.2.2的集成环境下进行本地redis扩展安装配置的,php的版本是5.6. ...

  7. DOS 常用命令集

    net use $">\\ip\ipc$Content$nbsp;" " /user:" " 建立IPC空链接 net use $"& ...

  8. Ory Kratos 用户认证

    Ory Kratos 为用户认证与管理系统.本文将动手实现浏览器(React+AntD)的完整流程,实际了解下它的 API . 代码: https://github.com/ikuokuo/start ...

  9. PhotoShop CC2015(64位)下载链接和破解教程

    photoshop如今有cc和cs两种版本,之前出了一个cs的破解教程和扣圆形图,有很多朋友说cc比cs好用的多,希望出个cc的下载链接和破解教程,故推出2015pscc版破解教程和下载链接. 百度云 ...

  10. Gogs+Drone搭建CI/CD平台

    Gogs 是由 Go 语言编写的 Git 服务器,由中国人主导开发的一款开源项目,搭建方便并且拥有完善的中文文档,配合 Drone 可以实现持续集成/持续部署.本文介绍如何通过 Docker 搭建 G ...