从org.apache.http.HttpResponse获取HTTP代码

91

我在我的Java应用程序中使用org.apache.http.HttpResponse类,需要能够获取HTTP状态码。如果我对它使用.toString(),我可以在其中看到HTTP状态码。是否有其他函数可以直接获取HTTP状态码作为int或String?

非常感谢!

4个回答

139

72

我使用 httpResponse.getStatusLine().getStatusCode() 并发现它可靠地返回整数形式的HTTP状态码。


39
httpResponse.getStatusLine().getStatusCode()

3
一个例子如下:
        final String enhancementPayload ="sunil kumar";
        HttpPost submitFormReq = new HttpPost("https://bgl-ast/rest/service/form/form-data");
        StringEntity enhancementJson = new StringEntity(enhancementPayload);
        submitFormReq.setEntity(enhancementJson);
        submitFormReq.setHeader("Content-Type", "application/xml");

        HttpResponse response = httpClient.execute( submitFormReq );
        String result = EntityUtils.toString(response.getEntity());
        System.out.println("result "+result);
        assertEquals(200, response.getStatusLine().getStatusCode());

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接