分享

HttpClient在HTTP协议接口测试中的使用

 zhl463 2016-01-05
public void post(String url, Map<String, String> params){
    CloseableHttpClient httpClient = null;
    HttpPost httpPost = null;
    try {
        httpClient = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000).build();
        httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);
        List<NameValuePair> ps = new ArrayList<NameValuePair>();
        for (String pKey : params.keySet()) {
            ps.add(new BasicNameValuePair(pKey, params.get(pKey)));
        }
        httpPost.setEntity(new UrlEncodedFormEntity(ps));
        CloseableHttpResponse response = httpClient.execute(httpPost);
        HttpEntity httpEntity = response.getEntity();
        System.out.println(EntityUtils.toString(httpEntity,"utf-8"));
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }finally{
        try {
            if(httpPost!=null){
                httpPost.releaseConnection();
            }
            if(httpClient!=null){
                httpClient.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约