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;
}
}
Try to modify
String sender = "GET /docs/ HTTP/1.1\n" + "Host:localhost:8080\n";
withString 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