【问题标题】:Accept Cookies inside Java code?在 Java 代码中接受 Cookie?
【发布时间】:2014-03-21 13:59:47
【问题描述】:

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

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

如您所见,要访问页面 Y 的内容,必须存在 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);

      }    

【问题讨论】:

  • 至少把你目前写的代码贴出来,而不是让我们为你做这一切
  • 你好,谢谢你的回复,我不是要求你做这一切不,我只需要负责这个的类/方法的名称:) 我更新了我的帖子抱歉。跨度>
  • 既然 Java 拥有完美的 HTTP API,为什么还要重新实现 HTTP?
  • 啊!我的眼睛!如果您使用 Eclipse 或 NetBeans 等 IDE,请使用代码格式化。在 Eclipse 中是:Ctrl - Shift - F.
  • 对不起,丑陋的代码 :) 我将尝试使用 java 的 httpclient 重写它。谢谢..

标签: java sockets cookies


【解决方案1】:

我会强烈推荐使用HttpClient 或其他专用于 HTTP 处理的库,而不是尝试自己实现/解释协议。请参阅here 了解如何使用 HttpClient 处理 cookie。

【讨论】:

    猜你喜欢
    • 2022-01-16
    • 2013-11-23
    • 1970-01-01
    • 2010-10-06
    • 2017-11-02
    • 1970-01-01
    • 2023-01-30
    • 1970-01-01
    • 2012-12-30
    相关资源
    最近更新 更多