开发者

Add HEADER in HTTP Request in Java

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

try
{
    Socket  s = ne开发者_高级运维w 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 ?


Don't try to implement the HTTP protocol yourself.

Use HttpComponents by Apache.

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


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


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


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


You can also see URLConnection.

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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜