2012-01-11 114 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服务器站点,将其更改为另一个名字,如果这是一个不同类型的服务器