Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

When I do:

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();
like image 282
Mediator Avatar asked May 01 '11 06:05

Mediator


1 Answers

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
}
like image 66
Jordan Avatar answered Oct 10 '22 23:10

Jordan