gpt4 book ai didi

android - 如何在 android 中使用 HttpUrlConnection 类将 cookie 添加到 url?

转载 作者:行者123 更新时间:2023-11-29 17:20:25 25 4
gpt4 key购买 nike

我正在尝试从 url 解析 json 数据,当我尝试创建连接时,它会抛出异常java.net.ProtocolException:读取响应后无法写入请求正文

我收到的响应消息是未找到

我在网络浏览器中检查了 url,当我使用我的凭据登录时,它显示了 Json 数据。

所以,我发现我需要将 cookie 添加到我的连接中,但我不知道该怎么做。

    public void parseData(String cookie){
HttpUrlConnection connection;

try{
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();

connection.setRequestProperty("Cookie", cookie);
Log.e(TAG, "cookie " + cookie);

connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("GET");

connection.connect();
Log.e(TAG,connection.getResponseMessage());

/**
here i'm trying to parse the data
using BufferedReader calss
**/

}
catch(IOException e){}
}

我需要在连接中添加 cookie。请帮我解决这个问题。

最佳答案

根据 this link 你可以这样做:

Values must be set prior to calling the connect method:

URL myUrl = new URL("http://www.hccp.org/cookieTest.jsp"); 
URLConnection urlConn = myUrl.openConnection();

Create a cookie string:

String myCookie = "userId=igbrown";

Add the cookie to a request: Using the setRequestProperty(String name, String value); method, we will add a property named "Cookie", passing the cookie string created in the previous step as the property value.

urlConn.setRequestProperty("Cookie", myCookie); 

Send the cookie to the server: To send the cookie, simply call connect() on the URLConnection for which we have added the cookie property:

urlConn.connect()

关于android - 如何在 android 中使用 HttpUrlConnection 类将 cookie 添加到 url?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36834932/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com