android已有cookie信息,如何让从中获得header
时间: 2023-08-22 19:08:26 浏览: 41
如果你已经在 Android 应用中获取到了 Cookie 信息,那么可以通过设置 HTTP 请求的 Header 来使用这些 Cookie。具体来说,可以通过以下步骤来实现:
1. 获取 CookieManager 实例:
```
CookieManager cookieManager = CookieManager.getInstance();
```
2. 获取指定网址的 Cookie:
```
String cookie = cookieManager.getCookie(url);
```
其中,`url` 是要获取 Cookie 的网址,`cookie` 是获取到的 Cookie 字符串。
3. 创建 HTTP 请求对象:
```
HttpURLConnection connection = (HttpURLConnection) new URL(requestUrl).openConnection();
```
其中,`requestUrl` 是要请求的网址。
4. 设置 Cookie Header:
```
connection.setRequestProperty("Cookie", cookie);
```
其中,`cookie` 是前面获取到的 Cookie 字符串。
5. 发起 HTTP 请求:
```
connection.connect();
```
以上就是使用 Cookie 发起 HTTP 请求的基本步骤。需要注意的是,如果要使用 Cookie 发起 HTTPS 请求,则需要在应用的 Manifest 文件中添加以下元素:
```
<application
...
android:networkSecurityConfig="@xml/network_security_config">
...
</application>
```
然后在 `res/xml` 目录下创建 `network_security_config.xml` 文件,内容如下:
```
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true"/>
<domain-config>
<domain includeSubdomains="true">your-https-domain.com</domain>
</domain-config>
</network-security-config>
```
其中,`your-https-domain.com` 是你要访问的 HTTPS 域名。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)