HttpClient 使用

 

 

/**
     * @param args
     */
    public static void httpsGet(String urlparams) {

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet request = new HttpGet(urlparams);
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(request);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    public static void httpPost(String url, String params) {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);
        try {
            StringEntity s = new StringEntity(params, "utf-8");
            s.setContentType("application/json");
            post.setEntity(s);
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();// 设置请求和传输超时时间
            post.setConfig(requestConfig);
            HttpResponse res = client.execute(post);
            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = res.getEntity();
                String resultjson = EntityUtils.toString(entity, "utf-8");
                System.out.println(resultjson);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            try {
                post.releaseConnection();
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

 

posted @ 2018-09-29 13:07  河周IT  阅读(130)  评论(0)    收藏  举报