Hello!
After successful programmatic authorization on the site, it is necessary to go to another page of this site without being logged out. As I understand it, you need to log in, get cookies, save them for the next request.
An attempt to get cookies from the first request fails: "No cookies". What could be the problem?
I do as follows:

import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.CookieStore; import org.apache.http.client.HttpClient; import org.apache.http.client.ResponseHandler; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.params.ClientPNames; import org.apache.http.client.params.CookiePolicy; import org.apache.http.client.protocol.ClientContext; import org.apache.http.cookie.Cookie; import org.apache.http.impl.client.*; import org.apache.http.message.BasicNameValuePair; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HTTP; import org.apache.http.protocol.HttpContext; import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); try { CookieStore cookieStore = new BasicCookieStore(); HttpContext localContext = new BasicHttpContext(); localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); HttpClient instance = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build(); HttpPost httpost = new HttpPost("http://url"); HttpResponse httppost = instance.execute(httpost); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("userid", "myid")); nvps.add(new BasicNameValuePair("userpass", "mypass")); httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = instance.execute(httpost, responseHandler); List<Cookie> cookies = httpclient.getCookieStore().getCookies(); if (cookies.isEmpty()) { System.out.println("No cookies"); } else { for (int i = 0; i < cookies.size(); i++) { System.out.println("- " + cookies.get(i).toString()); } } //Второй post-запрос /* HttpClient instance2 = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build(); HttpPost httpost2 = new HttpPost("http://url2"); httpclient.setCookieStore(cookieStore); HttpResponse httppost2 = instance.execute(httpost2); ResponseHandler<String> responseHandler2 = new BasicResponseHandler(); String responseBody2 = instance2.execute(httpost2, responseHandler2); System.out.println(responseBody2); System.out.println("++++++++++++++++++++++++++++++++++++");*/ } finally { httpclient.getConnectionManager().shutdown(); System.out.println("Это конец."); } } } 

Everything turns out if you do as Phoen-X indicated below, thanks! Further, I try to install the received cookies, create a new request, but in response I receive that I am not an authorized user. How to make the second request as an already authorized user? Perhaps I do something stupid, but I do it like this:

  BasicClientCookie cookie1 = new BasicClientCookie("mykey", cookie.getValue()); cookie1.setDomain("domain"); cookie1.setPath("/"); cookieStore.addCookie(cookie1); HttpClient instance2 = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build(); HttpPost httpost2 = new HttpPost("http://url2"); HttpResponse response2 = instance2.execute(httpost2, httpContext); ResponseHandler<String> responseHandler2 = new BasicResponseHandler(); String responseBody2 = instance2.execute(httpost2, responseHandler2); System.out.println(responseBody2); System.out.println("++++++++++++++++++++++++++++++++++++"); System.out.println(response2); 

    1 answer 1

     DefaultHttpClient httpclient = new DefaultHttpClient(); HttpPost httpost = new HttpPost("http://url"); CookieStore cookieStore; try { List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("userid", "myid")); nvps.add(new BasicNameValuePair("userpass", "mypass")); httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); HttpResponse response = httpclient.execute(httpost); cookieStore = ((DefaultHttpClient) httpclient).getCookieStore(); //Выведем в консоль имена cookie с их значениями List<Cookie> cookieList = cookieStore.getCookies(); if(!cookieList.isEmpty()) { for(Cookie cookie : cookieList) { System.out.println(cookie.getName() + " = " + cookie.getValue()); } } } catch (ClientProtocolException e) { e.printStackTrace(); } //Отправим второй запрос HttpPost httppost2 = new HttpPost("http://url2"); try { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("Параметр1", "Значение1")); nameValuePairs.add(new BasicNameValuePair("Параметр2", "Значение2")); httppost2.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8)); ((DefaultHttpClient) httpclient).setCookieStore(cookieStore); //Бывает и так, что надо прикреплять заголовки к запросу (FireBug поможет увидеть, какие именно нужны), например: httppost2.addHeader("Host", "site.ru"); httppost2.addHeader("Referer", "http://site.ru/"); //Заголовки прикрепили HttpContext localContext = new BasicHttpContext(); localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); HttpResponse response = httpclient.execute(httppost2, localContext); //И выведем в консоль, что нам пришло в ответе HttpEntity entity = response.getEntity(); InputStream is = entity.getContent(); System.out.println(inputStreamToString(is)); is.close(); } catch (ClientProtocolException e) { Log.e("Error", e.getMessage()); e.printStackTrace(); } catch (IOException e) { Log.e("Error", e.getMessage()); e.printStackTrace(); } //Метод для считывания ответа сервера из входного потока + преобразование в строку private String inputStreamToString(InputStream is) { String s = ""; String line = ""; BufferedReader rd = new BufferedReader(new InputStreamReader(is)); try { while ((line = rd.readLine()) != null) { s += line; } } catch (IOException e) { e.printStackTrace(); } return s; } 
    • Thank you so much! This way it works. Now I encounter a new problem, when creating the second query, I am not perceived as an authorized user. The details are described above in addition to the first post - Kib51
    • I store cookies for such things in SharedPreferences. Am I doing right - without a clue) Now I’ll add the code so that the second request is executed as well)) Yes, and use the FireBug add-on for Mozilla FireFox browser (if you don’t use it, of course) to see what is sent from you parameters and what headers)) - PhoEn-X