Android setRequestProperty in a url.openConnection()

穿精又带淫゛_ 提交于 2019-12-11 01:54:30

问题


I have an Android app that need to set a requestproperty in a connection. Here is my code:

 URL url = new URL(sUrl);

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

When I call the setRequestProperty method it launch the exception:

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

Is there a way to create the connection to the file without using the url.openConnection() ?


回答1:


You could try to use the CookieManager mentioned in http://developer.android.com/reference/java/net/HttpURLConnection.html

Set your cookie to 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);

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

Use url.openConnection() after you set your cookie.




回答2:


Here url.openCOnnection() will open new connection to the resource referred to by this URL. Here you again opening a connection by calling url.connect() method. So remove that

Check this.. for the sample example...



来源:https://stackoverflow.com/questions/19565195/android-setrequestproperty-in-a-url-openconnection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!