httpclient来测试本地接口

1.发送post请求接口

/**
     * 发送Post请求
     * 
     * @param httpPost
     * @return
     */
    private static String sendHttpPost(HttpPost httpPost) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        HttpEntity entity = null;
        String responseContent = null;
        try {
            // 创建默认的httpClient实例.
            httpClient = HttpClients.custom()
                    .setSSLSocketFactory(SSLConnectionSocketFactory.getSocketFactory())
                    .setDefaultRequestConfig(requestConfig).build();
            // 执行请求
            response = httpClient.execute(httpPost);
            entity = response.getEntity();
            responseContent = EntityUtils.toString(entity, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭连接,释放资源
                if (response != null) {
                    response.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseContent;
    }

2.进行测试

@Test
    public void postTest() throws IOException {

        String path = this.getClass().getResource("/").getPath();
        //findLawCaceList.json 文件中录入需要传入的参数
        File file = new File(path + "/com/webapp/api/test/findLawCaceList.json");

        String param = FileUtils.readFileToString(file, "UTF-8");
        String digest = Encrypt.getSHA256(param);
        HttpPost post = new HttpPost("http://localhost:接口路径");
        post.setEntity(new StringEntity(param, "UTF-8"));
        post.setHeader("digest", digest);
        String result = sendHttpPost(post);
        System.out.println(result);
    }

猜你喜欢

转载自blog.csdn.net/qq_41255610/article/details/79963533