如何获得标题? (java,httpclient 4.X) [英] How to get headers? (java,httpclient 4.X)
本文介绍了如何获得标题? (java,httpclient 4.X)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我这样做时:
Header[] h = first.getAllHeaders();
返回的标题
数组为空。有任何想法吗?下面是我的代码。
The returned Header
array is empty. Any ideas? Below is my code.
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();
推荐答案
您正在调用 getAllHeaders ()
on first
,这是你的HttpGet对象。您想在响应对象上调用 getAllHeaders()
,如下所示:
You're calling getAllHeaders()
on first
, which is your HttpGet object. You want to call getAllHeaders()
on the response object like this:
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
}
这篇关于如何获得标题? (java,httpclient 4.X)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文