Add HEADER in HTTP Request in Java

2020-07-27 03:55发布

问题:

I'm using this following code to send simple HTTP Request :

try
{
    Socket  s = new Socket ();
    s.bind    (new InetSocketAddress (ipFrom, 0));
    s.connect (new InetSocketAddress (ipTo,   80), 1000);

    PrintWriter     writer = new PrintWriter    (s.getOutputStream ());
    BufferedReader  reader = new BufferedReader (new InputStreamReader (s.getInputStream ()));

    writer.print ("GET " + szUrl + " HTTP/1.0\r\n\r\n"); 
    writer.flush ();

    s     .close ();
    reader.close ();
    writer.close ();
}

However, as you can see, I don't send a custom HEADER. What should I add to send a custom HEADER ?

Cheers,

Christophe OLIVIER

回答1:

When you write

writer.print ("GET " + szUrl + " HTTP/1.0\r\n\r\n"); 

The \r\n\r\n bit is sending a line-feed/carriage-return to end the line and then another one to indicate that there are no more headers. This is a standard in both HTTP and email formats, i.e. a blank line indicates the end of headers. In order to add additional headers you just need to not send that sequence until you're done. You can do the following instead

writer.print ("GET " + szUrl + " HTTP/1.0\r\n"); 
writer.print ("header1: value1\r\n"); 
writer.print ("header2: value2\r\n"); 
writer.print ("header3: value3\r\n"); 
// end the header section
writer.print ("\r\n"); 


回答2:

Don't try to implement the HTTP protocol yourself.

Use HttpComponents by Apache.

(or its older and a little easier to use version - HttpClient)



回答3:

Even if I suggest to try HttpComponents as mentioned by Bozho instead of implementing HTTP by yourself, this is would be the way to add a custom header:

 writer.print ("GET " + szUrl + " HTTP/1.0\r\n"); 
 writer.print ("X-MyOwnHeader: SomeValue\r\n");


回答4:

You should use classes already prepared to be used for http connections, like HTTPUrlConnection that is a childreon of UrlConnection and has this method

void setRequestProperty(String key, String value)

that should be used to set parameters of the request (like HEADER field).. check here for reference



回答5:

You can also see URLConnection.

https://docs.oracle.com/javase/1.5.0/docs/api/java/net/URLConnection.html



回答6:

If you absolutely have to do it yourself by hand it must follow this format with each header on its own line.

name: value

Look into the header format in HTTP spec.

http://www.w3.org/Protocols/HTTP/1.0/draft-ietf-http-spec.html#Message-Headers