如何获得标题?(java,httpclient 4.X)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5846886/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 13:05:42  来源:igfitidea点击:

How to get headers? (java,httpclient 4.X)

javahttpclient

提问by Mediator

When I do:

当我做:

Header[] h = first.getAllHeaders();

The returned Headerarray is empty. Any ideas? Below is my code.

返回的Header数组为空。有任何想法吗?下面是我的代码。



HttpClient httpclient = new DefaultHttpClient();

CookieStore cookieStore = new BasicCookieStore();

// Create local HTTP context
HttpContext localContext = new BasicHttpContext();
// Bind custom cookie store to the local context
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);


HttpGet first = new HttpGet("http://vk.com");
HttpResponse response = httpclient.execute(first, localContext);

InputStream instream = response.getEntity().getContent();
StringBuilder sb = new StringBuilder();
BufferedReader r = new BufferedReader(new InputStreamReader(instream, Charset.forName("windows-1251")));
for (String line = r.readLine(); line != null; line = r.readLine()) {
    sb.append(line);
}
Header[] h = first.getAllHeaders();
instream.close();
String s = sb.toString();

回答by Jordan

You're calling getAllHeaders()on first, which is your HttpGet object. You want to call getAllHeaders()on the responseobject like this:

你打电话getAllHeaders()first,这是你的HTTPGET对象。您要拨打getAllHeaders()的上响应这样的对象:

Header[] h = response.getAllHeaders();

You can also check the Response's status code and respond accordingly like this:

您还可以检查响应的状态代码并相应地响应如下:

int statusCode = response.getStatusLine().getStatusCode();
Logger.d("Response returned status code " + statusCode);

if (HttpStatus.SC_OK == statusCode) {
    // TODO: handle 200 OK
} else if (HttpStatus.SC_NOT_FOUND == statusCode) { 
    // TODO: handle 404 Not Found
} else { 
    // TODO: handle other codes here
}