Skip to content
Advertisement

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.0rnrn"); 
    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 ?

Advertisement

Answer

When you write

writer.print ("GET " + szUrl + " HTTP/1.0rnrn"); 

The rnrn 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.0rn"); 
writer.print ("header1: value1rn"); 
writer.print ("header2: value2rn"); 
writer.print ("header3: value3rn"); 
// end the header section
writer.print ("rn"); 
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement