Get HTTP code from org.apache.http.HttpResponse

半世苍凉 提交于 2019-12-31 10:56:10

问题


I'm using the org.apache.http.HttpResponse class in my Java application, and I need to be able to get the HTTP status code. If I used .toString() on it, I can see the HTTP status code in there. Is there any other function that I can just get the HTTP status code as either an int or String?

Thanks a bunch!


回答1:


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




回答2:


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




回答3:


httpResponse.getStatusLine().getStatusCode()



回答4:


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


来源:https://stackoverflow.com/questions/6153283/get-http-code-from-org-apache-http-httpresponse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!