java代码如何获取HttpClient返回的状态码和正文信息呢?
下文笔者讲述java代码获取HttpClient返回的状态码和正文信息的方法分享,如下所示
HttpClient简介
HttpClient(Apache HttpClient)我们常用于获取访问http协议上的内容 那么如何获取其返回的状态码信息(200,404,500等状态码信息) 及HttpClient返回的正文信息
实现思路: 1.定义httpClient对象 2.创建访问对象httpGet 3.使用httpClient的execute方法运行访问对象 即可返回状态码和正文内容例1:
try (CloseableHttpClient httpClient = HttpClients.createDefault()) { final HttpGet httpGet = new HttpGet(GET_URL); try (CloseableHttpResponse response = httpClient.execute(httpGet)) { //状态码 StatusLine statusLine = response.getStatusLine(); System.out.println(statusLine.getStatusCode() + " " + statusLine.getReasonPhrase()); //正文 String responseBody = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8); System.out.println("Response body: " + responseBody); } }例2:
Response response = Request.Get(uri) .connectTimeout(MILLIS_ONE_SECOND) .socketTimeout(MILLIS_ONE_SECOND) .execute(); HttpResponse httpResponse = response.returnResponse(); StatusLine statusLine = httpResponse.getStatusLine();
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。