简体   繁体   中英

Java HTTP Requests via Apache HTTP Client Library

I am using Apache HTTP Client Library to send HTTP request. I have following questions:

1- Does this library attaches any default headers to the request, or you have to attach all the headers yourself.

HttpClient client = new HttpClient();;
HttGet request = new HttpGet('http://www.example.com');

//Now Can i execute the request directly or do i need to 
//add headers before executing the request

client.execute(request);

2- I also want to see the headers that are being sent to the server. I tried "request.getHeaders()" but it just prints - "[Lorg.apache.http.Header;@1bc2616". How can I get it to print headers in a name - value format.

What version of Apache HttpClient are you using? In version 4.0.1 there is a method HttpGet#getAllHeaders() which returns an array of Header object. See grep code here - http://grepcode.com/file/repo1.maven.org/maven2/org.apache.httpcomponents/httpcore/4.0.1/org/apache/http/message/AbstractHttpMessage.java#AbstractHttpMessage.getAllHeaders%28%29

I tried running this code:

final HttpClient client = new DefaultHttpClient();
final HttpGet get = new HttpGet("http://www.google.com");

client.execute(get);
for (final Header header : get.getAllHeaders()) {
    System.out.println("Header: " + header.getName() + " = " + header.getValue());
}
System.out.println(get.getAllHeaders().length);

I did not see any headers getting printed in the console and get.getAllHeaders().length returned zero (0). So I would assume that HttpClient doesn't provide any default Headers.

I wouldn't recommend to use separate HttpGet/HttpPost/HttpPut but HttpRequest Interface. There you'll be able to set Header/body as HttpEntity. But Default header is attached: method: GET/POST/PUT by default; You should separately set Content-Type and Encoding

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM