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

我在 Java 应用程序中使用的是 org.apache.http.HttpResponse类,我需要能够获得 HTTP状态码。如果我用 ABc1我能看到里面的 HTTP状态码。还有没有其他函数我可以直接得到整型或者字符串的 HTTP状态码?

多谢了!

73314 次浏览

Use HttpResponse.getStatusLine(), which returns a StatusLine object containing the status code, protocol version and "reason".

httpResponse.getStatusLine().getStatusCode()

I have used httpResponse.getStatusLine().getStatusCode() and have found this to reliably return the integer http status code.

A example will be as below,

        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());