2013-06-19 64 views
-3

我有一臺服務器,我必須先登錄(第一個URL),然後我會發送另一個POST請求(第二個URL),但是這個帖子請求只能在我仍然登錄時才能完成。如何使用URL 2的POST請求仍然被記錄?如何在一個HTTPconnection中創建多個請求?

下面是代碼:

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") 
+0

沒有'HTTPConnection'這樣的東西。你的意思是'HttpURLConnection'嗎? – EJP

回答

-1

你有沒有嘗試添加憑據請求URL 2?

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

非常感謝回覆,登錄在URL 1中工作...即使我再次這樣做,我必須爲POST請求建立不同的連接...我如何確保POST確保我處於登錄狀態?順便說一句我使用HttpURLConnection而不是HttpClient。 – user2413711

+0

因此,第一個URL是服務器上的一些手動登錄頁面?當您登錄到網站或服務器時,您的憑證將被存儲,以便作爲導航結果發送的後續HTTP請求。因此,當您通過Java或任何其他語言發送請求時,您需要將憑據附加到每個請求。 – PandaBearSoup

+0

是的,第一個URL只是一個聯合國和PW頁面...登錄後有服務頁面......這是我無法獲得服務。我怎樣才能發送證書出去做POST請求。 – user2413711

0

你不需要做任何事情。

  1. HttpURLConnection在後臺執行TCP連接池。
  2. 即使通過多個連接,HTTP會話也通過cookie保存。
相關問題