我对http的请求非常慢

时间:2015-06-08 08:35:19

标签: sockets http get

我需要通过套接字发出请求并捕获响应但是在阻塞变慢时。我想我已经写了足够的信息,但如果有人可以帮助我并需要其他信息,我会回答他/她。谢谢。

import java.io.InputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;

public class HttpCase {

  Socket socket;

  private void sendGet() throws Exception {

    try {

      socket = new Socket( InetAddress.getByName( "localhost"), 8080);

      String sender = "GET /docs/ HTTP/1.1\n" + "Host:localhost:8080\n";

      System.out.println( "- - - - - SENDED REQUEST - - - - - \n" + sender);
      PrintWriter pw = new PrintWriter( socket.getOutputStream());
      pw.print( sender + "\n");
      pw.flush();

    }
    catch ( Exception e) {
      e.printStackTrace();
    }

  }

  public void catchResponse() throws Exception {

    StringBuilder sb = new StringBuilder();
    InputStream is = socket.getInputStream();
    byte buf[] = new byte[2 * 1024];
    int r = 0;

    while ( (r = is.read( buf)) > 0 ) {
      sb.append( new String( buf, 0, r));
    }

    is.close();

    String arrivedBody = sb.toString();

    System.out.println( "- - - - - RECEIVED REQUEST - - - - - \n" + arrivedBody);
    System.out.println( arrivedBody);

  }

  public static void main( String[] args) throws Exception {

    HttpCase http = new HttpCase();

    System.out.println( "Testing 1 - Send Http GET request");
    http.sendGet();
    http.catchResponse();

  }
}

解决问题的方法是改变这个问题:

 while ( ( r = is.read( buf)) > 0 ) {
  sb.append( new String( buf, 0, r));

  if ( is.available() <= 0 ) {
    break;
  }
}

1 个答案:

答案 0 :(得分:0)

尝试修改String sender = "GET /docs/ HTTP/1.1\n" + "Host:localhost:8080\n";String sender = "GET /docs/ HTTP/1.0\n" + "Host:localhost:8080\n";

HTTP / 1.1默认使用keepalive,这可能与您的问题有关。

最后,您可以尝试发送Connection: close标题