zoukankan      html  css  js  c++  java
  • HttpClient封装工具类

    1.返回统一格式

    public class HttpResult {
        // 响应的状态码
        private int code;
    
        // 响应的响应体
        private String body;
    
        public int getCode() {
            return code;
        }
    
        public void setCode(int code) {
            this.code = code;
        }
    
        public String getBody() {
            return body;
        }
    
        public void setBody(String body) {
            this.body = body;
        }
    
    }

    2.封装HttpClient常用方法

    import java.util.ArrayList;
    import java.util.List;
    import java.util.Map;
    
    import org.apache.http.NameValuePair;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpDelete;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.client.methods.HttpPut;
    import org.apache.http.client.utils.URIBuilder;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.message.BasicNameValuePair;
    import org.apache.http.util.EntityUtils;
    
    /**
     * 封装HttpClient常用方法
     * 
     * @author Wonder
     *
     */
    public class ApiService {
    
        // 每个方法都会用到,提取出来
        private CloseableHttpClient httpClient;
    
        public ApiService() {
            this.httpClient = HttpClients.createDefault();
        }
    
        /**
         * 不带参数的get
         * 
         * @param uri
         * @return
         * @throws Exception
         */
        public HttpResult doGet(String uri) throws Exception {
            return this.doGet(uri, null);
        }
    
        /**
         * 带参数的get请求
         * 
         * @param url
         * @param map
         * @return
         * @throws Exception
         */
        public HttpResult doGet(String url, Map<String, Object> map) throws Exception {
            // 1.创建URIBuilder
            URIBuilder uriBuilder = new URIBuilder(url);
    
            // 2.设置请求参数
            if (map != null) {
                // 遍历请求参数
                for (Map.Entry<String, Object> entry : map.entrySet()) {
                    // 封装请求参数
                    uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
                }
            }
    
            // 3.创建请求对象httpGet
            HttpGet httpGet = new HttpGet(uriBuilder.build());
    
            // 4.使用httpClient发起请求
            CloseableHttpResponse response = this.httpClient.execute(httpGet);
    
            // 5.解析返回结果,封装返回对象httpResult
            // 5.1获取状态码
            int code = response.getStatusLine().getStatusCode();
    
            // 5.2 获取响应体
            // 使用EntityUtils.toString方法必须保证entity不为空
            String body = null;
            if (response.getEntity() != null) {
                body = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
            HttpResult result = new HttpResult();
            result.setCode(code);
            result.setBody(body);
            return result;
        }
    
        /**
         * 不带参数的post请求
         * 
         * @param url
         * @return
         */
        public HttpResult doPost(String url) throws Exception {
            return this.doPost(url, null);
        }
    
        /**
         * 带参数的post请求
         * 
         * @param url
         * @param map
         * @return
         * @throws Exception
         */
        public HttpResult doPost(String url, Map<String, Object> map) throws Exception {
            // 1. 声明httppost
            HttpPost httpPost = new HttpPost(url);
    
            // 2.封装请求参数,请求数据是表单
            // 声明封装表单数据的容器
            List<NameValuePair> parameters = new ArrayList<NameValuePair>(0);
            if (map != null) {
    
                for (Map.Entry<String, Object> entry : map.entrySet()) {
                    // 封装请求参数到容器中
                    parameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
                }
            }
            // 创建表单的Entity类
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, "UTF-8");
    
            // 3. 把封装好的表单实体对象设置到HttpPost中
            httpPost.setEntity(entity);
    
            // 4. 使用Httpclient发起请求
            CloseableHttpResponse response = this.httpClient.execute(httpPost);
    
            // 5. 解析返回数据,封装HttpResult
            // 5.1状态码
            int code = response.getStatusLine().getStatusCode();
            // 5.2 响应体内容
            String body = null;
            if (response.getEntity() != null) {
                body = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
    
            HttpResult result = new HttpResult();
            result.setCode(code);
            result.setBody(body);
            return result;
        }
    
        /**
         * 不带参数的put请求
         * 
         * @param url
         * @return
         */
        public HttpResult doPut(String url) throws Exception {
            return this.doPut(url, null);
        }
    
        /**
         * 带参数的put请求
         * 
         * @param url
         * @param map
         * @return
         * @throws Exception
         */
        public HttpResult doPut(String url, Map<String, Object> map) throws Exception {
            // 1. 声明httpput
            HttpPut httpPut = new HttpPut(url);
    
            // 2.封装请求参数,请求数据是表单
            if (map != null) {
                // 声明封装表单数据的容器
                List<NameValuePair> parameters = new ArrayList<NameValuePair>();
                for (Map.Entry<String, Object> entry : map.entrySet()) {
                    // 封装请求参数到容器中
                    parameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
                }
    
                // 创建表单的Entity类
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, "UTF-8");
    
                // 3. 把封装好的表单实体对象设置到HttpPost中
                httpPut.setEntity(entity);
            }
            // 4. 使用Httpclient发起请求
            CloseableHttpResponse response = this.httpClient.execute(httpPut);
    
            // 5. 解析返回数据,封装HttpResult
            // 5.1状态码
            int code = response.getStatusLine().getStatusCode();
            // 5.2 响应体内容
            String body = null;
            if (response.getEntity() != null) {
                body = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
    
            HttpResult result = new HttpResult();
            result.setCode(code);
            result.setBody(body);
            return result;
        }
    
        /**
         * 不带参数的delete
         * 
         * @param uri
         * @return
         * @throws Exception
         */
        public HttpResult doDelete(String uri) throws Exception {
            return this.doDelete(uri, null);
        }
    
        /**
         * 带参数的delete
         * 
         * @param url
         * @param map
         * @return
         * @throws Exception
         */
        public HttpResult doDelete(String url, Map<String, Object> map) throws Exception {
            // 1.创建URIBuilder
            URIBuilder uriBuilder = new URIBuilder(url);
    
            // 2.设置请求参数
            if (map != null) {
                // 遍历请求参数
                for (Map.Entry<String, Object> entry : map.entrySet()) {
                    // 封装请求参数
                    uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
                }
            }
    
            // 3.创建请求对象httpGet
            HttpDelete httpDelete = new HttpDelete(uriBuilder.build());
    
            // 4.使用httpClient发起请求
            CloseableHttpResponse response = this.httpClient.execute(httpDelete);
    
            // 5.解析返回结果,封装返回对象httpResult
            // 5.1获取状态码
            int code = response.getStatusLine().getStatusCode();
    
            // 5.2 获取响应体
            // 使用EntityUtils.toString方法必须保证entity不为空
            String body = null;
            if (response.getEntity() != null) {
                body = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
            HttpResult result = new HttpResult();
            result.setCode(code);
            result.setBody(body);
            return result;
        }
    
    }

    3.测试

    import java.util.HashMap;
    import java.util.Map;
    
    import org.junit.Test;
    
    public class HttpClientTest {
    
        /**
         * 根据ID来获取数据
         * GET
         * @throws Exception 
         */
        @Test
        public void testGet() throws Exception {
            
            ApiService service = new ApiService();
            
            HttpResult result = service.doGet("http://manager.web.com:8079/rest/item/interface/40");
            System.err.println("状态码:"+ result.getCode());
            System.err.println("数据:"+ result.getBody());
            
        }
        
        @Test
        public void testPut() throws Exception {
            ApiService service = new ApiService();
            String url = "http://manager.web.com:8079/rest/item/interface";
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("id", "40");
            map.put("title", "酷派大神");
            HttpResult result = service.doPut(url, map);
            System.err.println("状态码:"+ result.getCode());
            System.err.println("数据:"+ result.getBody());
        }
    
    }
  • 相关阅读:
    AtCoder Beginner Contest 169
    Codeforces Round #646 (Div. 2)
    Educational Codeforces Round 88 (Rated for Div. 2)
    Codeforces Round #645 (Div. 2)
    【uoj】【美团杯2020】平行四边形(原根)
    【uoj】【美团杯2020】半前缀计数(后缀自动机)
    Codeforces Round #644 (Div. 3)
    [COI2009] OTOCI
    [AHOI2005] 航线规划
    [P1390] 公约数的和
  • 原文地址:https://www.cnblogs.com/soul-wonder/p/9085869.html
Copyright © 2011-2022 走看看