Set cookie from HTTP request

I get the correct login using HttpRequest to work. It prints the correct html form of the log page in my toast (for testing only). Now I want to set a cookie from this request. How is this possible? If necessary, I can provide some code.

I already know about the CookieManager class, but how can I do this?

Thanks in advance!

My code is:

    public String getPostRequest(String url, String user, String pass) {
    HttpClient postClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);
    HttpResponse response;

    try {
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("login", user));
        nameValuePairs.add(new BasicNameValuePair("pass", pass));
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));      

        response = postClient.execute(httpPost);

        if(response.getStatusLine().getStatusCode() == 200) {
            HttpEntity entity = response.getEntity();

            if (entity != null) {
                InputStream instream = entity.getContent();  
                String result = convertStreamToString(instream);                   
                instream.close();             

                return result;      
            }
        }
    } catch (Exception e) {}
    Toast.makeText(getApplicationContext(),
            "Connection failed",
            Toast.LENGTH_SHORT).show();
    return null; 
}

private String convertStreamToString(InputStream is) {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return sb.toString();
}           

Well, that is pretty much. The convertStreamToString () function converts an InputStream to a String (plain HTML), which I “toast” to just test it (the way it works), so the code works. Now set the cookie .:-)

This is what I got to now:

// inside my if (entity != null) statement
List<Cookie> cookies = postClient.getCookieStore().getCookies();
String result = cookies.get(1).toString();
                    return result;

, CookieList 1 , . , ?

+3

Source: https://habr.com/ru/post/1764833/


All Articles