Apache HttpClient实现访问RESTFUL接口

来源:互联网 发布:电玩巴士有几家淘宝店 编辑:程序博客网 时间:2024/06/18 15:47

1、添加jar

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.2</version>
        </dependency>


2、代码

              CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet("http://172.18.1.177:8080/declare-rest/restful/company/getPaging?currentPage=1&pageRecord=2");
            CloseableHttpResponse httpResponse = null;
            try {
                httpResponse = httpClient.execute(httpGet);
                System.out.print("Protocol Version :: ");
                System.out.println(httpResponse.getProtocolVersion());
                System.out.println("--------------------------------------------------");
                System.out.print("Status Code :: ");
                System.out.println(httpResponse.getStatusLine().getStatusCode());
                System.out.println("--------------------------------------------------");
                System.out.print("Reason Phrase :: ");
                System.out.println(httpResponse.getStatusLine().getReasonPhrase());
                System.out.println("--------------------------------------------------");
                System.out.print("Status Line :: ");
                System.out.println(httpResponse.getStatusLine().toString());
                System.out.println("--------------------------------------------------");
                HttpEntity httpEntity = httpResponse.getEntity();
                System.out.print("Content Length :: ");
                System.out.println(httpEntity.getContentLength());
                System.out.println("--------------------------------------------------");
                System.out.print("Content Type :: ");
                System.out.println(httpEntity.getContentType());
                System.out.println("--------------------------------------------------");
                System.out.print("Content :: ");
                System.out.println(httpEntity.getContent());
                System.out.println("--------------------------------------------------");
                System.out.print("Content Text :: ");
                System.out.println(EntityUtils.toString(httpEntity));
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    httpClient.close();
                    httpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

原创粉丝点击