I connected to the site via HttpURLConnection and sent a post request (for authorization). After the authentication is successful, I need to send another get request. Everything works well like a clock, but the problem is that when I send a get request, the site asks for authorization again. Help pliz) thanks in advance!

Water code:

HttpURLConnection conn = (HttpURLConnection) new URL("http://сайт.com/account").openConnection(); conn.setDoInput(true); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true); String params = "qs=&user=Логин&pss=Пароль"; CookieHandler.setDefault(new CookieManager()); conn.setRequestProperty("Content-Length", "" + Integer.toString(params.getBytes().length)); OutputStream os = conn.getOutputStream(); byte[] data = params.getBytes("UTF-8"); os.write(data); data = null; params = "user=Логин&v2=1&v3=1&v4=1&v5=1&forcelogout=1"; conn = (HttpURLConnection) new URL("http://сайт.com/autosurf").openConnection(); conn.setDoInput(true); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestProperty("Content-Length", "" + Integer.toString(params.getBytes().length)); data = params.getBytes("UTF-8"); os.write(data); data = null; BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); while(true){ while(br.ready()){ System.out.println(br.readLine()); }} 
  • 2
    Session data, cookies should be pushed every time you access the site. The only problem is this. You do not send any parameter according to which the site considers that you are authorized. - ArchDemon
  • 3
    Session is usually supported with the help of cookies. And every time you do this here CookieHandler.setDefault(new CookieManager()); The new cookie manager does not accept cookies from its predecessor. Accordingly, the following request is not possible to confirm the continuation of the session. - Sergey
  • @Sergey Thanks for the quick response. How to do differently? - as1andrey1
  • @ArchDemon Thanks for the quick response! how to send it? - as1andrey1
  • Can it not touch at all, leave the system. Or install only once at the beginning of the session. - Sergey

1 answer 1

in the first request we receive cookies from the site and save them to the variable

 cookie = conn.getHeaderField("Set-Cookie"); 

then when we make the second request we get a cookie from the variable and send it to the site

 conn.setRequestProperty("Cookie", cookie);