java · 2020-08-31 0

使用HttpClient进行GET、POST、PUT、DELETE操作

一、maven依赖

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.4.RELEASE</version>
</parent>

<properties>
    <httpclient.version>4.5.5</httpclient.version>
    <fastjson.version>1.2.47</fastjson.version>
    <junit.version>4.12</junit.version>
</properties>

<dependencies>

    <!-- web -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <!-- httpclient -->
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>${httpclient.version}</version>
    </dependency>

    <!-- fastjson -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>${fastjson.version}</version>
    </dependency>

    <!-- junit -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>${junit.version}</version>
        <scope>test</scope>
    </dependency>
</dependencies>

二、服务端

使用SpringBoot启动服务

@RequestParam用于接受url传递的参数

@RequestBody用于接受请求体中的参数

@RestController
@RequestMapping("/httpclient")
public class HttpClientController {

    @GetMapping("/get")
    public String get(@RequestParam String name, @RequestParam Integer age) {
        return String.format("%s %s", name, age);
    }

    @PostMapping("/post")
    public String post(@RequestBody Map map) {
        return map.toString();
    }

    @PutMapping("/put")
    public String put(@RequestBody Map map) {
        return map.toString();
    }

    @DeleteMapping("/delete")
    public String delete(@RequestParam String name, @RequestParam Integer age) {
        return String.format("%s %s", name, age);
    }
}

三、客户端

public class HttpClientTest {

    @Test
    public void testGet1() throws IOException {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

        StringBuilder params = new StringBuilder();
        params.append("name=" + URLEncoder.encode("&", "UTF-8"));
        params.append("&");
        params.append("age=20");

        HttpGet httpGet = new HttpGet("http://localhost:8080/httpclient/get?" + params);

        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpGet);
            HttpEntity responseEntity = response.getEntity();
            System.out.println("响应状态为:" + response.getStatusLine());
            if (responseEntity != null) {
                System.out.println("响应内容长度:" + responseEntity.getContentLength());
                System.out.println("响应内容为:" + EntityUtils.toString(responseEntity, StandardCharsets.UTF_8));
            }
        } finally {
            if (httpClient != null) {
                httpClient.close();
            }
            if (response != null) {
                response.close();
            }
        }
    }

    @Test
    public void testGet2() throws IOException, URISyntaxException {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("name", "&"));
        params.add(new BasicNameValuePair("age", "18"));
        URI uri = new URIBuilder()
                .setScheme("http")
                .setHost("localhost")
                .setPort(8080)
                .setPath("/httpclient/get")
                .setParameters(params).build();

        HttpGet httpGet = new HttpGet(uri);

        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpGet);
            HttpEntity responseEntity = response.getEntity();
            System.out.println("响应状态为:" + response.getStatusLine());
            if (responseEntity != null) {
                System.out.println("响应内容长度:" + responseEntity.getContentLength());
                System.out.println("响应内容为:" + EntityUtils.toString(responseEntity, StandardCharsets.UTF_8));
            }
        } finally {
            if (httpClient != null) {
                httpClient.close();
            }
            if (response != null) {
                response.close();
            }
        }
    }

    @Test
    public void testPost() throws IOException {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

        HttpPost httpPost = new HttpPost("http://localhost:8080/httpclient/post");

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("a", "A");
        jsonObject.put("b", "B");
        String jsonString = jsonObject.toJSONString();

        StringEntity entity = new StringEntity(jsonString, StandardCharsets.UTF_8);
        // post请求是将参数放在请求体里面传过去
        httpPost.setEntity(entity);
        httpPost.setHeader("Content-Type", "application/json;charset=utf8");

        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);
            HttpEntity responseEntity = response.getEntity();
            System.out.println("响应状态为:" + response.getStatusLine());
            if (responseEntity != null) {
                System.out.println("响应内容长度:" + responseEntity.getContentLength());
                System.out.println("响应内容为:" + EntityUtils.toString(responseEntity, StandardCharsets.UTF_8));
            }
        } finally {
            if (httpClient != null) {
                httpClient.close();
            }
            if (response != null) {
                response.close();
            }
        }
    }

    @Test
    public void testPut() throws IOException {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

        HttpPut httpPut = new HttpPut("http://localhost:8080/httpclient/put");

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("a", "A");
        jsonObject.put("b", "B");
        String jsonString = jsonObject.toJSONString();

        StringEntity entity = new StringEntity(jsonString, StandardCharsets.UTF_8);
        // put请求是将参数放在请求体里面传过去
        httpPut.setEntity(entity);
        httpPut.setHeader("Content-Type", "application/json;charset=utf8");

        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpPut);
            HttpEntity responseEntity = response.getEntity();
            System.out.println("响应状态为:" + response.getStatusLine());
            if (responseEntity != null) {
                System.out.println("响应内容长度:" + responseEntity.getContentLength());
                System.out.println("响应内容为:" + EntityUtils.toString(responseEntity, StandardCharsets.UTF_8));
            }
        } finally {
            if (httpClient != null) {
                httpClient.close();
            }
            if (response != null) {
                response.close();
            }
        }
    }

    @Test
    public void testDelete() throws IOException {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

        StringBuilder params = new StringBuilder();
        params.append("name=" + URLEncoder.encode("&", "UTF-8"));
        params.append("&");
        params.append("age=20");

        HttpDelete httpDelete = new HttpDelete("http://localhost:8080/httpclient/delete?" + params);

        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpDelete);
            HttpEntity responseEntity = response.getEntity();
            System.out.println("响应状态为:" + response.getStatusLine());
            if (responseEntity != null) {
                System.out.println("响应内容长度:" + responseEntity.getContentLength());
                System.out.println("响应内容为:" + EntityUtils.toString(responseEntity, StandardCharsets.UTF_8));
            }
        } finally {
            if (httpClient != null) {
                httpClient.close();
            }
            if (response != null) {
                response.close();
            }
        }
    }

}