如何在一个HTTP连接中发出多个请求?

时间:2013-06-19 15:18:51

标签: java httpconnection

我有一台服务器,我必须先登录(第一个URL),然后我会发送另一个POST请求(第二个URL),但是这个帖子请求只能在我仍然登录的情况下完成。如何使用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")

2 个答案:

答案 0 :(得分:0)

你不需要做任何事情。

  1. i在幕后进行TCP连接池。
  2. 通过cookie保留HTTP会话,甚至跨多个连接。

答案 1 :(得分:-1)

您是否尝试过向URL 2添加请求凭据?

UsernamePasswordCredentials creds = new UsernamePasswordCredentials(
            username, password);
request.addHeader(new BasicScheme().authenticate(creds, request));
HttpResponse response = httpClient.execute(request);