Apache HttpClient – Get the Status Code – Apache HttpClient – 获取状态代码

最后修改: 2013年 12月 24日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this very quick tutorial, I will show how to get and validate the StatusCode of the HTTP Response using HttpClient.

在这个非常快速的教程中,我将展示如何使用HttpClient获取和验证HTTP响应的StatusCode。

If you want to dig deeper and learn other cool things you can do with the HttpClient – head on over to the main HttpClient tutorial.

如果你想更深入地了解你可以用HttpClient做的其他很酷的事情–请到主要HttpClient教程

2. Retrieve the Status Code from the Http Response

2.从Http响应中检索状态代码

After sending the Http request – we get back an instance of org.apache.http.HttpResponse – which allows us to access the status line of the response, and implicitly the Status Code:

在发送完Http请求后,我们会得到一个org.apache.http.HttpResponse的实例,它允许我们访问响应的状态行,以及隐含的状态代码。

response.getStatusLine().getStatusCode()

Using this, we can validate that the code we receive from the server is indeed correct:

利用这一点,我们可以验证我们从服务器收到的代码确实是正确的

@Test
public void givenGetRequestExecuted_whenAnalyzingTheResponse_thenCorrectStatusCode() 
  throws ClientProtocolException, IOException {
    HttpClient client = HttpClientBuilder.create().build();    
    HttpResponse response = client.execute(new HttpGet(SAMPLE_URL));
    int statusCode = response.getStatusLine().getStatusCode();
    assertThat(statusCode, equalTo(HttpStatus.SC_OK));
}

Notice that we’re using the predefined Status Codes also available in the library via org.apache.http.HttpStatus.

注意,我们使用的是预定义的状态代码,该库中也可以通过org.apache.http.HttpStatus获得。

3. Conclusion

3.结论

This very simple example shows how to retrieve and work with Status Codes with the Apache HttpClient.

这个非常简单的例子展示了如何用Apache HttpClient 检索和处理状态代码。

The implementation of all these examples and code snippets can be found in my github project – this is an Eclipse based project, so it should be easy to import and run as it is.

所有这些例子和代码片段的实现可以在我的github项目中找到 – 这是一个基于Eclipse的项目,所以它应该很容易导入并按原样运行。