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

时间:2011-05-01 06:32:06

标签: java httpclient

当我这样做时:

Header[] h = first.getAllHeaders();

返回的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();

1 个答案:

答案 0 :(得分:13)

您正在getAllHeaders()上调用first,这是您的HttpGet对象。您想在响应对象上调用getAllHeaders(),如下所示:

Header[] h = response.getAllHeaders();

您还可以检查响应的状态代码并做出相应的响应,如下所示:

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
}