httpclient封装别人接口

近期收到任务需要封装下别的开发组写的接口以实现权限控制,于是想起了httpclient,直接上代码吧

    @Test
    public void post() {  
		// 创建默认的httpClient实例.    
        CloseableHttpClient httpclient = HttpClients.createDefault();
//        CookieStore cookieStore = new BasicCookieStore();
//        cookieStore.addCookie();
//		CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore ).build();
        // 创建httppost    
//       HttpPost httppost = new HttpPost("http://localhost:8080/api/v2/bi/report/getPersonas"); 
       HttpPost httppost = new HttpPost("http://10.0.4.62:8000/api/v1/car_income"); 
//        HttpPost httppost = new HttpPost("http://localhost:8080/api/v1/user/login"); 
        try {  
        	JSONObject jsonParam = new JSONObject();
//        	jsonParam.put("staffEname", "zeezhang");
//        	jsonParam.put("oaPwd", "7c4a8d09ca3762af61e59520943dc26494f8941b");
//        	jsonParam.put("statDim", "gender");
//        	jsonParam.put("groupby","all");
//        	jsonParam.put("filters","{}");
//        	jsonParam.put("start_date","2017-10-01");
//        	jsonParam.put("end_date","2017-10-17");
//        	jsonParam.put("dimensions","['company_code','last_expired_time']");
        	StringEntity entity = new StringEntity("{\"groupby\":\"all\",\"start_date\":\"2017-01-01\",\"end_date\":\"2017-10-19\",\"dimensions\":[],\"filters\":{}}", "utf-8");  
        	entity.setContentEncoding("UTF-8");    
            entity.setContentType("application/json");
//            httppost.addHeader("Cookie", "JSESSIONID=0d9fc7de-19ab-4a8e-85b4-fe3b5526a4c4");
            httppost.addHeader("Authorization", "Basic ZG1hcGlfdGVzdDpkbUAyMDE3MDkwNQ==");
            httppost.setEntity(entity);  
            System.out.println("executing request:==== " + httppost.getURI());  
            CloseableHttpResponse response = httpclient.execute(httppost); 
//            String value = response.getFirstHeader("Set-Cookie").getValue();
//            System.out.println(value+"====================");
            try {  
                HttpEntity entity1 = response.getEntity();  
                if (entity1 != null) {  
                    System.out.println("--------------------------------------"); 
                    System.out.println(entity1);
                    System.out.println("--------------------------------------"); 
                    System.out.println("Response content: " + EntityUtils.toString(entity1, "UTF-8"));  
                    System.out.println("--------------------------------------");  
                }  
            } finally {  
                response.close();  
            }  
        } catch (ClientProtocolException e) {  
            e.printStackTrace();  
        } catch (UnsupportedEncodingException e1) {  
            e1.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        } finally {  
            // 关闭连接,释放资源    
            try {  
                httpclient.close();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
    }  
上边是json字符串格式的请求参数针对post请求

/** 
     * post方式提交表单(模拟用户登录请求) 
     */  
    @Test
    public void postForm() {  
        // 创建默认的httpClient实例.    
        CloseableHttpClient httpclient = HttpClients.createDefault();  
        // 创建httppost    
        HttpPost httppost = new HttpPost("http://localhost:8080/api/v1/user/login");  
        // 创建参数队列    
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();  
        formparams.add(new BasicNameValuePair("oaPwd", "7c4a8d09ca3762af61e59520943dc26494f8941b"));  
        formparams.add(new BasicNameValuePair("staffEname", "aaa"));
        UrlEncodedFormEntity uefEntity;  
        try {  
            uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");  
            httppost.setEntity(uefEntity);  
            System.out.println("executing request " + httppost.getURI());  
            CloseableHttpResponse response = httpclient.execute(httppost);  
            try {  
                HttpEntity entity = response.getEntity();  
                if (entity != null) {  
                    System.out.println("--------------------------------------");  
                    System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));  
                    System.out.println("--------------------------------------");  
                }  
            } finally {  
                response.close();  
            }  
        } catch (ClientProtocolException e) {  
            e.printStackTrace();  
        } catch (UnsupportedEncodingException e1) {  
            e1.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        } finally {  
            // 关闭连接,释放资源    
            try {  
                httpclient.close();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
    }  
上边是针对表单提交的post方式,get方式的就不再多说了


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
HttpClient是一个非常常用的HTTP客户端库,可以用于发送HTTP请求并接收响应。在封装HttpClient时,我们可以考虑以下几点: 1. 连接池管理:HttpClient可以通过连接池来管理HTTP连接,从而提高性能。我们可以设置最大连接数、每个路由的最大连接数等参数,以便更好地利用连接池。 2. 超时设置:在发送HTTP请求时,我们需要设置超时时间,以避免请求过程中出现阻塞或超时等问题。可以设置连接超时时间、读取超时时间等参数。 3. 异常处理:在发送HTTP请求时,可能会出现各种异常情况,例如网络异常、连接超时等。我们需要对这些异常进行处理,以便及时发现问题并进行处理。 4. 请求头设置:在发送HTTP请求时,我们需要设置请求头,以便服务器能够正确地处理请求。可以设置User-Agent、Content-Type等参数。 5. SSL支持:如果需要发送HTTPS请求,则需要支持SSL协议。可以通过配置SSLContext来实现SSL支持。 下面是一个简单的HttpClient封装示例: ```java public class HttpClientUtil { private static final int MAX_TOTAL = 200; private static final int MAX_PER_ROUTE = 50; private static final int CONNECT_TIMEOUT = 5000; private static final int SOCKET_TIMEOUT = 10000; private static CloseableHttpClient httpClient; static { PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); cm.setMaxTotal(MAX_TOTAL); cm.setDefaultMaxPerRoute(MAX_PER_ROUTE); RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(CONNECT_TIMEOUT) .setSocketTimeout(SOCKET_TIMEOUT) .build(); httpClient = HttpClients.custom() .setConnectionManager(cm) .setDefaultRequestConfig(requestConfig) .build(); } public static String doGet(String url, Map<String, String> headers) throws IOException { HttpGet httpGet = new HttpGet(url); if (headers != null) { for (Map.Entry<String, String> entry : headers.entrySet()) { httpGet.setHeader(entry.getKey(), entry.getValue()); } } try (CloseableHttpResponse response = httpClient.execute(httpGet)) { HttpEntity entity = response.getEntity(); if (entity != null) { return EntityUtils.toString(entity); } } return null; } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值