代码之家  ›  专栏  ›  技术社区  ›  Youssef

接受Java代码中的Cookie?

  •  2
  • Youssef  · 技术社区  · 15 年前

    我正在处理一个HTTP套接字项目,我必须从我的Java代码中发送2个HTTP GET请求:

    • 请求1:呼叫第X页
    • 第X页正在设置cookie。
    • 请求2:调用第Y页

    如您所见,要访问y页的内容,必须存在i cookie…

    如何从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 回复  |  直到 11 年前
        1
  •  1
  •   Brian Agnew    15 年前

    我愿意 强烈地 推荐使用 HttpClient 或者另一个专门用于HTTP处理的库,而不是自己尝试实现/解释协议。见 here 如何使用httpclient处理cookie。

    推荐文章