3

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.

Madhan
  • 495
  • 2
  • 10
  • 22
  • possible duplicate: http://stackoverflow.com/a/16171708/4310784 – Mohammad Zarei Apr 25 '16 at 08:16
  • i tried that way too. but i got an exception as "java.net.ProtocolException: cannot write request body after response has been read" can you tell me why it throws this exception. @Mohammad Z – Madhan Apr 25 '16 at 08:27
  • @Madhan: Sorry, removed my answer as I realised I was wrong. – Tigger Apr 25 '16 at 08:49

1 Answers1

8

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()
Mohammad Zarei
  • 1,773
  • 14
  • 33
  • actually i'm doing the same as your answer but it throws an exception i mention in my question and the response code as 404 . – Madhan Apr 25 '16 at 08:37
  • 1
    And if you want to add more than 1 cookie you can separate them by semicolons, e. g.: `String myCookie = "userId=igbrown;anyOther=345345";` – PAX May 15 '20 at 10:43