HttpClient和RestTemplate总结

本文详细介绍了HttpClient与RestTemplate的特点及使用方法。HttpClient提供了一种更灵活的方式进行HTTP请求,而RestTemplate则简化了与RESTful服务的交互过程。文章通过实例展示了不同HTTP方法的应用。

1 HttpClient

1.1 简介

HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性,它不仅使客户端发送Http请求变得容易,而且也方便开发人员测试接口(基于Http协议的),提高了开发的效率,也方便提高代码的健壮性。因此熟练掌握HttpClient是很重要的必修内容,掌握HttpClient后,相信对于Http协议的了解会更加深入。org.apache.commons.httpclient.HttpClient与org.apache.http.client.HttpClient的区别Commons的HttpClient项目现在是生命的尽头,不再被开发, 已被Apache HttpComponents项目HttpClient和HttpCore 模组取代,提供更好的性能和更大的灵活性。

1.2 HttpClient的请求类型

实现了所有的Http请求类型,相应的类为HttpGet、HttpPost、HttpDelete、HttpPut

1.3 导入依赖

在pom.xml中引入HttpClient的依赖

			<dependency>
				<groupId>org.apache.httpcomponents</groupId>
				<artifactId>httpclient</artifactId>
            	<version>4.5.6</version>
			</dependency>

在pom.xml中引入fastjson的依赖

			<dependency>
            	<groupId>com.alibaba</groupId>
            	<artifactId>fastjson</artifactId>
            	<version>1.2.62</version>
			</dependency>

1.4 HttpGet

	public static void main(String[] args) throws IOException {
        //1.打开浏览器
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //2.声明get请求
        HttpGet httpGet = new HttpGet("http://www.baidu.com/s?wd=java");
        //3.发送请求
        CloseableHttpResponse response = httpClient.execute(httpGet);
        //4.判断状态码
        if(response.getStatusLine().getStatusCode()==200){
            HttpEntity entity = response.getEntity();
           //使用工具类EntityUtils,从响应中取出实体表示的内容并转换成字符串
            String string = EntityUtils.toString(entity, "utf-8");
            System.out.println(string);
        }
        //5.关闭资源
        response.close();
        httpClient.close();
    }

1.5 HttpPost

	public static void main(String[] args) throws IOException {
        //1.打开浏览器
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //2.声明post请求
        HttpPost httpPost = new HttpPost("https://www.baidu.com/");
        //3.请求体
        StringEntity stringEntity = new StringEntity("{\"cname\":\"wuyin\",\"type\":\"SIMPLE\"});
        httpPost.setEntity(stringEntity);
 
        //4.发送请求
        CloseableHttpResponse response = httpClient.execute(httpPost);
        //5.判断状态码
        if(response.getStatusLine().getStatusCode()==200){
            HttpEntity entity = response.getEntity();
            String string = EntityUtils.toString(entity, "utf-8");
            System.out.println(string);
        }
        //6.关闭资源
        response.close();
        httpClient.close();
    }

1.6 HttpPut

	public static void main(String[] args) throws IOException {
        //1.打开浏览器
        //HttpClientBuilder.create().build();
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //2.声明post请求
        HttpPut httpPut = new HttpPut("https://www.baidu.com/");
        //3.请求体
        StringEntity stringEntity = new StringEntity("{\"cname\":\"wuyin\",\"type\":\"SIMPLE\"});
        httpPost.setEntity(stringEntity);
 
        //4.发送请求
        CloseableHttpResponse response = httpClient.execute(httpPut);
        //5.判断状态码
        if(response.getStatusLine().getStatusCode()==200){
            HttpEntity entity = response.getEntity();
            String string = EntityUtils.toString(entity, "utf-8");
            System.out.println(string);
        }
        //6.关闭资源
        response.close();
        httpClient.close();
    }

1.7 HttpDelete

	public static void main(String[] args) throws IOException {
        //1.打开浏览器
        //HttpClientBuilder.create().build();
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //2.声明post请求
        HttpDelete httpDelete = new HttpDelete("https://www.baidu.com/");
        //3.请求体
        StringEntity stringEntity = new StringEntity("{\"cname\":\"wuyin\",\"type\":\"SIMPLE\"});
        httpPost.setEntity(stringEntity);
 
        //4.发送请求
        CloseableHttpResponse response = httpClient.execute(httpDelete);
        //5.判断状态码
        if(response.getStatusLine().getStatusCode()==200){
            HttpEntity entity = response.getEntity();
            String string = EntityUtils.toString(entity, "utf-8");
            System.out.println(string);
        }
        //6.关闭资源
        response.close();
        httpClient.close();
    }

2 RestTemplate

2.1 简介

RestTemplate是Spring提供的用于访问Rest服务的客户端,RestTemplate提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率。简化了与http服务的通信,并满足RestFul原则,程序代码可以给它提供URL,并提取结果。默认情况下,RestTemplate默认依赖jdk的HTTP连接工具。可以通过setRequestFactory属性切换到不同的HTTP源,比如Apache HttpComponents、Netty和OkHttp。

2.2 请求方式

HttpMethodRestTemplateMethodsDescription
GETgetForObjectgetForObject函数实际上是对getForEntity函数的进一步封装,只关注返回的消息体的内容
getForEntitygetForEntity方法的返回值是一个ResponseEntity,ResponseEntity是Spring对HTTP请求响应的封装,包括了几个重要的元素,如响应码、contentType、contentLength、响应消息体等。
POSTpostForObject同理
postForEntity同理
postForLocationpostForLocation也是提交新资源,提交成功之后,返回新资源的URI,postForLocation的参数和前面两种的参数基本一致,只不过该方法的返回值为Uri,这个只需要服务提供者返回一个Uri即可,该Uri表示新资源的位置。
DELETEdelete请求服务器删除Request-URI所标识的资源
PUTput请求服务器存储一个资源,并用Request-URI作为其标识
OPTIONSoptionsForAllow请求查询服务器的性能,或者查询与资源相关的选项和需求
HEADheadForHeaders请求获取由Request-URI所标识的资源的响应消息报头

2.3 相关问题

  1. restTemplate的delete和put方法没有返回值,可能没法获取请求的返回。可以使用exchange方法和execute方法,可以指定请求类型。区别是exchange返回ResponseEntity,而execute返回消息体映射的对象。
  2. 使用方法中的uriVariables参数需要在url参数中使用占位符(暂时发现这一种)
	public void main(){
        // 请求头
        HttpHeaders headers = new HttpHeaders();
        // 请求体
        headers.setContentType(MediaType.APPLICATION_JSON);
        Map map = new HashMap(){{
            this.put("token","aaaa");
            this.put("project","bbbb");
        }};
        //提供json转化功能
        String str = "{\"cname\":\"wuyin3_bytemplate_123\"}";
        // 发送请求
        HttpEntity<String> entity = new HttpEntity<>(str, headers);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<JSONObject> resultEntity = restTemplate.exchange
                ("http://XXXX?token={token}&project={project}", HttpMethod.PUT, entity, JSONObject.class,map);
        System.out.println(resultEntity.getBody());
    }
  1. RestTemplate能大幅简化了提交表单数据的难度,并且附带了自动转换JSON数据的功能
    在这里插入图片描述

2.4 相关链接

https://blog.csdn.net/u012702547/article/details/77917939

https://www.cnblogs.com/javazhiyin/p/9851775.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值