bill0ute
bill0ute

Reputation: 369

Add HEADER in HTTP Request in Java

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 ?

Upvotes: 3

Views: 11958

Answers (6)

oneat
oneat

Reputation: 10994

You can also see URLConnection.

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

Upvotes: 1

Jherico
Jherico

Reputation: 29240

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

Upvotes: 5

Jack
Jack

Reputation: 133557

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

Upvotes: 1

Malax
Malax

Reputation: 9604

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

Upvotes: 1

Chandra Sekar
Chandra Sekar

Reputation: 10843

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

Upvotes: 0

Bozho
Bozho

Reputation: 597016

Don't try to implement the HTTP protocol yourself.

Use HttpComponents by Apache.

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

Upvotes: 6

Related Questions