将两个HTTP 1.1请求发送到同一套接字中的服务器时出现问题

时间:2011-08-16 14:18:32

标签: http sockets request

我正在尝试向同一个套接字中的服务器发送两个HTTP请求,我得到了第一个请求的响应,但第二个请求没有, 我尝试使用相同或不同的缓冲读取器和BufferedWriter发送它们,但总是我只响应请求一而不是两个响应。

我太紧张了,请帮助我,并提前感谢你,

 Socket socket = new Socket(addr, port);
 String strRequest1="myxmlRequest1....";
 //send request 
 wr.write("POST / HTTP/1.1\r\n");
          wr.write("Host: HOST\r\n");
          wr.write("User-Agent: Java\r\n");
          wr.write("Content-Length: " + strRequest1.length() +  "\r\n");
          wr.write("Content-Type: text/xml\r\n");
          wr.write("Connection: Keep_alive\r\n\r\n");
          wr.write(strRequest1 +"\r\n");
          wr.flush();

// Get response
           rd = new BufferedReader(new InputStreamReader(
                      socket.getInputStream(), "UTF8"));

          System.out.println( "BufferedReader rd------------------------------>" + rd);
          System.out.println( "readLine------------------------------>" + rd.toString());
          while ((line = rd.readLine()) != null) {
              System.out.println("output---------->" + output);
              output = output + line + "\n";
          }

          System.out.println("taille response" + output.length());
// Request 2
String s2="myxmlRequest2...";
//send request        
          BufferedWriter wr2 = new BufferedWriter(new OutputStreamWriter(
                   socket.getOutputStream(), "UTF8"));

          System.out.println(s2);
          wr2.write("POST / HTTP/1.1\r\n");
          wr2.write("Host: HOST\r\n");
          wr2.write("User-Agent: Java\r\n");
          wr2.write("Content-Length: " + s2.length() +  "\r\n");
          wr2.write("Content-Type: text/xml\r\n");
          wr2.write("Connection: Close\r\n\r\n");
          wr2.write(s2 + "\r\n");
          wr2.flush(); 

// get response 
          BufferedReader rd2 = new BufferedReader(new InputStreamReader(
                  socket.getInputStream(), "UTF8"));
          output="";
          while ((line = rd2.readLine()) != null) {
              System.out.println("output2---------->" + output);
              output = output + line + "\n";
          }

          System.out.println("s2 response" + output.length()+"s2"+output);

2 个答案:

答案 0 :(得分:2)

      wr.write("Connection: Keep_alive\r\n\r\n");
                                ^---- should be a -

它是Keep-Alive,带有破折号,而不是下划线。

答案 1 :(得分:1)

我找到了解决这个问题的方法。 有人在这里被问到并解决了:

persistent connection java