Aldridge1991
Aldridge1991

Reputation: 1367

Get cookies after post request

I'm trying to login into a website and store the cookies in order to make further requests being authenticated.

I successfully log in in the site and get a response but i can't manage to store the cookie properly. This is the code I use to log in:

private String makePostRequest(String url, List<String> header_fields, List<String> header_values) {

    String sessionCookie = "";

    HttpResponse response = null;
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);

    //Post Data
    List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(header_fields.size());

    for(int i = 0; i < header_fields.size(); i++){

        nameValuePair.add(new BasicNameValuePair(header_fields.get(i), header_values.get(i)));
    }
    //Encoding POST data
    try {
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
    } catch (UnsupportedEncodingException e) {
        // log exception
        e.printStackTrace();
    }

    //making POST request.
    try {
        response = httpClient.execute(httpPost);
        // write response to log
        Log.d("Http Post Response:", response.toString());
    } catch (ClientProtocolException e) {
        // Log exception
        e.printStackTrace();
    } catch (IOException e) {
        // Log exception
        e.printStackTrace();
    }

    int statusCode = response.getStatusLine().getStatusCode();
    InputStream is = null;
    StringBuilder stringBuilder = new StringBuilder();
    if (statusCode == HttpStatus.SC_OK) {
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            try {
                is = entity.getContent();
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            byte[] buffer = new byte[1024];
            int length;
            try {
                while ((length = is.read(buffer)) > 0) {
                    stringBuilder.append(new String(buffer, 0, length));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

     return stringBuilder.toString();
}

With that code I login and get the response string where i can see i have successfully logged in. Any idea about the cookies? Can't manage to get it to work.

UPDATE

This is the code i use to get session cookies

HttpGet httpGet = new HttpGet(url);
Header[] header=response.getHeaders("Set-Cookie");
for(int i =0; i < header.length; i++) {
     httpGet.addHeader("Set-Cookie", (header[i].getValue()));
}

Upvotes: 3

Views: 11252

Answers (3)

Roadies
Roadies

Reputation: 3329

Here I found this solution which work for me. Wordpress api i used.

     @Override
                    public void success(JsonObject jsonObject, Response response) {


                        List<Header> mCookies = response.getHeaders();

                        for (int i = 0; i <mCookies.size() ; i++) {
                            mCookies.get(i).getName();

                            Log.e("response-value", String.valueOf(mCookies.get(i).getName()) +":"+ String.valueOf(mCookies.get(i).getValue()));

                            if (mCookies.get(i).getName().equals("set-cookie")){
                                Log.e("response-value", String.valueOf(mCookies.get(i).getValue()));
                            }
                        }


                        }

                    }

Upvotes: 0

Sameer Zinzuwadia
Sameer Zinzuwadia

Reputation: 3285

when you request first time-store cookies in shared preference

for (int i = 0; i < headers.length; i++) {
                    Header h = headers[i];
                    if (h.getName().equals("Set-Cookie")) {
                        cookie = h.getValue();
                         break;
                    }
                }

While sending another request

if (!urlString.contains(Constants.URLPostfix.API_SIGNIN)) {
                // we need to add cookies in header if it is not signin
                cookie = App.preferenceGetString(SharedPreferenceKey.COOKIES, null);
                httpPostRequest.setHeader("cookie", cookie);

            }

Thank you

Upvotes: 0

Murtaza Khursheed Hussain
Murtaza Khursheed Hussain

Reputation: 15336

To Get cookies from the HTTP response do

Header[] mCookies = response.getHeaders("cookie");

After the following line

response = httpClient.execute(httpPost);

Upvotes: 2

Related Questions