如何获得标题?(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
How to get headers? (java,httpclient 4.X)
提问by Mediator
When I do:
当我做:
Header[] h = first.getAllHeaders();
The returned Header
array 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
}