【问题标题】:Android setRequestProperty in a url.openConnection()url.openConnection() 中的 Android setRequestProperty
【发布时间】:2013-10-24 20:40:20
【问题描述】:

我有一个需要在连接中设置请求属性的 Android 应用。这是我的代码:

 URL url = new URL(sUrl);

 HttpURLConnection connection = (HttpURLConnection) url.openConnection();  
 connection.setRequestProperty("cookie", cookievalue);
 connection.connect();

当我调用 setRequestProperty 方法时,它会启动异常:

java.lang.IllegalStateException: Cannot set request property after connection is made

有没有办法在不使用 url.openConnection() 的情况下创建到文件的连接?

【问题讨论】:

    标签: java android httpurlconnection illegalstateexception


    【解决方案1】:

    此处 url.openCOnnection() 将打开与此 URL 引用的资源的新连接。 在这里,您再次通过调用 url.connect() 方法打开连接。所以删除它

    查看this.. 以获取示例示例...

    【讨论】:

    • 异常是在 sendRequestProperty 行中抛出的,而不是在 url.connect() 中
    【解决方案2】:

    您可以尝试使用http://developer.android.com/reference/java/net/HttpURLConnection.html中提到的CookieManager

    将您的 cookie 设置为 CookieManager

        CookieManager cookieManager = new CookieManager();
        CookieHandler.setDefault(cookieManager);
    
        HttpCookie cookie = new HttpCookie("lang", "fr");
        cookie.setDomain("twitter.com");
        cookie.setPath("/");
        cookie.setVersion(0);
        cookieManager.getCookieStore().add(new URI("http://twitter.com/"), cookie);
    

    来源:http://developer.android.com/reference/java/net/HttpURLConnection.html

    设置 cookie 后使用 url.openConnection()。

    【讨论】:

      猜你喜欢
      • 2014-09-20
      • 2012-07-12
      • 2017-09-03
      • 1970-01-01
      • 1970-01-01
      • 2016-11-10
      • 1970-01-01
      • 2022-01-19
      • 1970-01-01
      相关资源
      最近更新 更多