Send HTTP request manually via socket

后端 未结 4 609
[愿得一人]
[愿得一人] 2020-11-28 05:15

When I send a normal HTTP request via a socket, the server does not respond with an OK response. I copied the HTTP header from Firefox. Here is the code:

Soc         


        
相关标签:
4条回答
  • 2020-11-28 05:56

    The correct fix which really works and it is cross platform:

        pw.print("GET / HTTP/1.1\r\n");
        pw.print("Host: stackoverflow.com\r\n\r\n");
    
    0 讨论(0)
  • 2020-11-28 06:07

    Two things:

    1. You should use println instead of print to print your entries to separate lines.
    2. HTTP request should end in a blank line (link). So add pw.println("");
    0 讨论(0)
  • 2020-11-28 06:07

    The following fix, as mentioned by the previous answers, solves the problem;

    pw.print("GET / HTTP/1.1\n\r\n");
    pw.print("Host: stackoverflow.com\n\r\n");
    
    0 讨论(0)
  • 2020-11-28 06:09

    You don't follow the HTTP RFC.

    • Header lines are always ended by a CR LF (i.e. 0x0d plus 0x0a).
    • The header ends after the first double-newline. In your case, you don't include the trailing newline so the server doesn't recognize the end of the request headers.

    Generally, you should always try to use existing HTTP libraries. Although HTTP seems to be a simple protocol (and it is compared to others), it has rather strict syntactic and semantic rules. If you try to implement this yourself, you should have read and understand the relevant parts of RFC 2616 (and related).

    Sadly, there are already too many crappy HTTP implementations not following the standards out there making the life for everyone miserable. Save yourself the hassle and use the HTTP libraries of your chosen language.

    0 讨论(0)
提交回复
热议问题