简体   繁体   English

通过Apache HTTP客户端库发出的Java HTTP请求

[英]Java HTTP Requests via Apache HTTP Client Library

I am using Apache HTTP Client Library to send HTTP request. 我正在使用Apache HTTP客户端库发送HTTP请求。 I have following questions: 我有以下问题:

1- Does this library attaches any default headers to the request, or you have to attach all the headers yourself. 1-该库是否将任何默认标头附加到请求,还是您必须自己附加所有标头。

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. 2-我也想看看正在发送到服务器的标头。 I tried "request.getHeaders()" but it just prints - "[Lorg.apache.http.Header;@1bc2616". 我尝试了“ request.getHeaders()”,但它只是打印-“ [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? 您正在使用哪个版本的Apache HttpClient? In version 4.0.1 there is a method HttpGet#getAllHeaders() which returns an array of Header object. 在4.0.1版中,有一个HttpGet#getAllHeaders()方法,该方法返回Header对象的数组。 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 在此处查看grep代码-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). 我没有看到任何标题在控制台中打印,并且get.getAllHeaders()。length返回零(0)。 So I would assume that HttpClient doesn't provide any default Headers. 因此,我假设HttpClient不提供任何默认标头。

I wouldn't recommend to use separate HttpGet/HttpPost/HttpPut but HttpRequest Interface. 我不建议使用单独的HttpGet / HttpPost / HttpPut,而是使用HttpRequest接口。 There you'll be able to set Header/body as HttpEntity. 在那里,您可以将Header / body设置为HttpEntity。 But Default header is attached: method: GET/POST/PUT by default; 但是附加了Default标头:方法:默认情况下为GET / POST / PUT; You should separately set Content-Type and Encoding 您应该分别设置Content-Type和Encoding

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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