2012-01-11 51 views
1

我正在尋找使用連接請求在外部站點中設置會話或cookie的方式。使用連接請求設置會話

我有據點A發送請求到站點B:

  url = new URL(urlSCS + "test"); 
      connection = (HttpURLConnection)url.openConnection(); 
      connection.setRequestMethod("POST"); 
      connection.setRequestProperty("Content-Type", 
       "application/x-www-form-urlencoded"); 

      connection.setRequestProperty("Content-Length", "" + 
        Integer.toString(urlParameters.getBytes().length)); 
      connection.setRequestProperty("Content-Language", "en-EN"); 

      connection.setUseCaches (false); 
      connection.setDoInput(true); 
      connection.setDoOutput(true); 

      //Send request 
      DataOutputStream wr = new DataOutputStream (
         connection.getOutputStream()); 
      wr.writeBytes (urlParameters); 
      wr.flush(); 
      wr.close(); 

      //Get Response  
      InputStream is = connection.getInputStream(); 
      BufferedReader rd = new BufferedReader(new InputStreamReader(is)); 
      String line; 
      StringBuffer response = new StringBuffer(); 
      while((line = rd.readLine()) != null) { 
      response.append(line); 
      response.append('\r'); 
      } 
      rd.close(); 

      responseSCS = response.toString(); 
      return responseSCS; 

     } catch (Exception e) { 

      e.printStackTrace(); 
      return null; 

     } finally { 

      if(connection != null) { 
      connection.disconnect(); 
      } 
     } 

而且在站點B我想創建會話或餅乾。可能嗎?

據我所知,要設置cookie或會話頁面應該顯示,beccouse cookie和會話被寫入瀏覽器。但也許有一些方法?

+0

您可以創建在java中使用'cookie'類的cookie,然後在請求中發送這個cookie。如果那就是你需要的。你的問題有點不清楚。 – RanRag 2012-01-11 10:12:34

+0

可能的重複[如何從外部網站獲取cookie?](http://stackoverflow.com/questions/8820033/how-do-i-get-a-cookie-from-an-external-webiste) – 2012-01-11 14:34:40

回答

3

第一個連接後,你可以得到你的會話ID這樣的:

String mySession = connection.getHeaderField("JSESSIONID"); 

而且在未來的連接,你可以保持您的會話是這樣的:

connection.setRequestProperty("Cookie", "JSESSIONID=" + mySession); 

這種方式,您也可以檢索/發送任何cookie作爲您的Java程序是瀏覽器或保持不同頁面請求之間的會話... 更多信息:

http://docs.oracle.com/javase/1.5.0/docs/guide/deployment/deployment-guide/cookie_support.html

見「到餅乾的編程訪問」

我們使用「JSESSIONID」假設站點B是一個Java服務器站點,將其更改爲另一個名字,如果這是一個不同類型的服務器