My get request for http is very slow

1.6k views Asked by At

I need to make a request through a socket and catch the response but in while block goes slow. I think i have written enough information, but if someone can help me and need additional information i will answer him/her. Thank you.

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();

  }
}

The solution for the problem is change while block for this one:

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

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

There are 1 answers

3
Michael Laffargue On BEST ANSWER

Try to modify String sender = "GET /docs/ HTTP/1.1\n" + "Host:localhost:8080\n"; with String sender = "GET /docs/ HTTP/1.0\n" + "Host:localhost:8080\n";

HTTP/1.1 is using keepalive by default, this may be related to your problem.

Last resort you can try to send a Connection: close header