Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send an HTTP header in java

Is it possible to send a Http header via a URL connection in java? I had this working using sockets, but ran into issues with a firewall which don't seem to be a problem with URLConnection. From looking at the API I get the impression that the output methods in URLConnection are just for filling in forms etc, or can they be used to send my own HTTP headers?

like image 988
Simonw Avatar asked May 04 '09 09:05

Simonw


People also ask

How do I send a header in HTTP request?

In the Name field, enter the name of your header rule (for example, My header ). From the Type menu, select Request, and from the Action menu, select Set. In the Destination field, enter the name of the header affected by the selected action. In the Source field, enter where the content for the header comes from.

How do you add a header to an HTTP request in Java?

Instead of setting the Header on each and every request, we can also configure it as a default header on the Client itself: Header header = new BasicHeader(HttpHeaders. CONTENT_TYPE, "application/json"); List<Header> headers = Lists. newArrayList(header); HttpClient client = HttpClients.

How do I send a custom header?

Custom Headers are for troubleshooting, informational purposes, and specific server-side logic. For example, to send a GET request with a custom header name, you can use the "X-Real-IP" header, which defines the client's IP address. For a load balancer service, "client" is the last remote host.


2 Answers

Yes, the method you want is setRequestProperty.

like image 74
Matthew Flaschen Avatar answered Oct 02 '22 07:10

Matthew Flaschen


The method you want is setRequestProperty, but I would recommend to use Apaches HttpClient. With this library you have total control over the request you want to send.

http://hc.apache.org/httpclient-3.x/tutorial.html

like image 39
HaBaLeS Avatar answered Sep 28 '22 07:09

HaBaLeS