简体   繁体   中英

How to print the status code on the console using socket

I'm trying to get the response code and I found a way to get the status code via this code Ch2 = reader.readLine();

This code Ch2 = reader.readLine(); Will let you read the first line and you will get the status code

And the response for example will be like this HTTP 200 OK

But the problem is when I send other content for example this content "GET /Qatar/ HTTP/1.1\\r\\n\\r\\n"

The response will be the second line of the first sending like this expires: Sat, 01 Jan 2000 00:00:00 GMT

Can anyone help me to solve this problem?

Here is my code

    sops.write(my_UTF8Byte);
            
    String Ch2 = "";
    Ch2 = reader.readLine(); 
    System.out.println(Ch2); // The first line is HTTP 200 OK
                
            // The Second content


    sops.flush();
    sops.write(my_UTF8Byte);
    sops.flush();
    Ch2 = reader.readLine();
    System.out.println(Ch2); // It will not print HTTP 200 OK It will print 

If you are going to try to talk to an HTTP server using a socket, you must read the HTTP specifications ... thoroughly. You need to understand the protocol and write your client-side code to conform to the protocol. Otherwise it won't work.

Key mistakes you are making:

  • You need to consume all of the header lines that are sent by the server, and then the body of the response. You are reading just the status line ... and leaving the rest of them. So when you try to read the response from the second "GET" request, what you are actually reading is header lines from the response to the first request.

  • You seem to be trying to send two requests over one socket connection, one after the other. This is possible, but there are a bunch of things that you need to do to make it work. Refer to the Persistent Connections section of the spec.

But actually, my recommendation is that you don't do this. Don't use a bare socket to talk to a HTTP server. It is too much work, and too easy to get it subtly (or grossly!) wrong.

Use an HTTP client library instead!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM