使用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();
            }
        }
    }

}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值