TestCase模拟Post请求

     本文对Post请求进行简单的模拟,读者可以在TestCase中实践之。

①引入httpclient的依赖:

           
            org.apache.httpcomponents
            httpclient
            

②封装方法:

    public static void doPost(String url,Map params) {
        CloseableHttpResponse response = null;
        try {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);
            List nvps = new ArrayList<>();
            for(Map.Entry entry: params.entrySet()) {
                nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
            httpPost.setEntity(new UrlEncodedFormEntity(nvps,"UTF-8"));
            response = httpclient.execute(httpPost);
            System.out.println("===========>>>"+response.getStatusLine());
            HttpEntity entity = response.getEntity();
            String content = EntityUtils.toString(entity);
            System.out.println("===========>>>"+content);
        }catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            try {
                if (response != null) {
                    response.close();
                }
            }catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    以上方法笔者亲测有效!

你可能感兴趣的:(Java学习)