2010-05-08 49 views
2

我處理一個HTTP插座的項目,我要送2個HTTP GET從我的Java代碼這樣的請求:接受Java代碼中的Cookie?

  • 請求1:調用頁X
  • 第X頁是設置一個cookie。
  • 請求2:正如你看到的訪問Ÿ我使用網站必須存在頁的內容致電Y形

...

如何接受Java代碼中的Cookie嗎?

以下是樣本發送的請求:

 String sServer = "example.com"; 
      InetAddress inaddr = null; 

      try { 
       inaddr = InetAddress.getByName(sServer); 
     } 
     catch (UnknownHostException ex) { //The host could not be resolved. 
       System.out.println(ex); 
       System.out.println("Error resolving hostname for '" + sServer + "'.\n"); 

     } 
     Socket sock = null; 
     try { 
       sock = new Socket(inaddr, 80); 
     } 
     catch (IOException ex) { 
      System.out.println(ex); 
      System.out.println("Could not create the socket.\n"); 

     } 

try { 
java.io.OutputStream os = sock.getOutputStream(); 
String sPacket = "GET /xxx/xxx/xxx.do HTTP/1.1\n"                + "Host: example.com\n" 
+ "Connection: keep-alive\n"             + "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/532.5 (KHTML, like Gecko) Chrome/4.1.249.1064 Safari/532.5\n" 
+ "Accept: application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8\n\n"; 

       os.write(sPacket.getBytes(), 0, sPacket.length()); 

       //Let's get the answer. 
       System.out.print("The server (" + sServer + ") answered: '"); 
       java.io.InputStream is = sock.getInputStream(); 
       byte[] buf = new byte[1024]; 
       is.read(buf, 0, buf.length); 
       for (int i = 0; i < buf.length; i++) { 
         if (buf[i] == 0) break; 
         else 
          System.out.print(new Character((char)buf[i])); 
       } 
       System. out.print("'\n"); 

     } 
     catch (Exception ex) { 
      System.out.println(ex); 

     }  
+1

至少發佈了你迄今爲止編寫的代碼,而不是要求我們爲你做這一切 – skaffman 2010-05-08 21:59:44

+1

你好,謝謝你的回覆,我不是要求你做這一切不,我只需要名稱的類/方法負責:) 我更新了我的帖子對不起。 – Youssef 2010-05-08 22:02:43

+0

當Java有一個完美的HTTP API時,爲什麼要重新實現HTTP? – skaffman 2010-05-08 22:10:30

回答

1

我會強烈推薦使用HttpClient或專用於HTTP處理另一個庫,而不是試圖實現/解釋自己的協議。有關如何使用HttpClient處理Cookie,請參閱here