Madhan
Madhan

Reputation: 505

How to add cookie to url using HttpUrlConnection class in android?

I'm trying to parse the json data from an url, when i try to create connection , it throws the exception as java.net.ProtocolException: cannot write request body after response has been read

I got the response message as Not found.

and i checked the url in web browser it shows the Json data when i login wuth my credentials.

so, i found that i need to add the cookie to my connection, but i don't know how to do this.

    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){}
    }

i need to add the cookie in connection. Please help me on this.

Upvotes: 3

Views: 27729

Answers (1)

Mohammad Zarei
Mohammad Zarei

Reputation: 1802

According to this link you can do this:

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()

Upvotes: 9

Related Questions