-3

我有一个服务器,我必须先登录(第一个 URL),然后我将发送另一个 POST 请求(第二个 URL),但是只有在我仍然登录的情况下才能完成这个 post 请求。如何仍然记录使用 URL 2 的 POST 请求?

这是代码:

  HttpURLConnection con=(HttpURLConnection) new URL("http://Login(URL1)").openConnection();
            String headerName=null; String cookie=null; 
            for (int i=1; (headerName = con.getHeaderFieldKey(i))!=null; i++) {
                if (headerName.equals("Set-Cookie"))               
                 cookie = con.getHeaderField(i);            
            }
            cookie = cookie.substring(0, cookie.indexOf(";"));
            String cookieName = cookie.substring(0, cookie.indexOf("="));
            String cookieValue = cookie.substring(cookie.indexOf("=") + 1, cookie.length());
            System.out.println(cookieName);
            System.out.println(cookieValue);
            con=(HttpURLConnection) new URL("http://Login(URL1)").openConnection();
            con.setRequestMethod("POST");
            con.setRequestProperty("Cookie", "session_id=" + cookieValue);
            con.setDoInput(true);
            con.setDoOutput(true);
            PrintWriter writer = new PrintWriter(con.getOutputStream());
            String account = "sdfsdf";
            String password = "sddfdsf";
            writer.println("&username=" + account + "&password=" + password + "&action=do_login&http=1");
            writer.close();

            System.err.println(con.getResponseCode());
            BufferedReader reader=new BufferedReader(new InputStreamReader(con.getInputStream()));
            String response;
            while ((response=reader.readLine())!=null) {
                System.out.println(response);
            }
            reader.close();


            con=(HttpURLConnection) new URL("http://POST Request URL").openConnection();
            con.setRequestMethod("POST")
4

2 回答 2

0

你不需要做任何事情。

  1. HttpURLConnection在幕后进行 TCP 连接池。
  2. HTTP 会话通过 cookie 保存,即使跨多个连接也是如此。
于 2017-04-30T10:26:19.473 回答
-1

您是否尝试将凭据添加到对 URL 2 的请求?

UsernamePasswordCredentials creds = new UsernamePasswordCredentials(
            username, password);
request.addHeader(new BasicScheme().authenticate(creds, request));
HttpResponse response = httpClient.execute(request);
于 2013-06-19T15:28:03.453 回答