Java中的远程访问工具

java中的访问远程Http服务的工具【restTemplate/HttpClient/HttpUrlConnection】

1.1:工具来源对比

来源 RestTemplate Http Client HttpUrlConnection HTTP Client
1 Spring框架提供 Apache jdk Netty

1.2:RestTemplate简介

RestTemplate 是从 Spring3.0 开始支持的一个 HTTP 请求工具,它提供了常见的REST请求方案的模版,例如 GET 请求、POST 请求、PUT 请求、DELETE 请求以及一些通用的请求执行方法 exchange 以及 execute。RestTemplate 继承自 InterceptingHttpAccessor 并且实现了 RestOperations 接口,其中 RestOperations 接口定义了基本的 RESTful 操作,这些操作在 RestTemplate 中都得到了实现。接下来我们就来看看这些操作方法的使用。

1.3:demo小实例

1.3.1 get 请求 getForObject() 和 getForEntity()
 getForObject()方法:
 ``public <T> T getForObject(String url, Class<T> responseType, Object... uriVariables) throws RestClientException {
       ***
    return this.execute(url, HttpMethod.GET, requestCallback, responseExtractor, (Object[])uriVariables);
  }
  public <T> T getForObject(String url, Class<T> responseType, Map<String, ?> uriVariables) throws RestClientException {
       ***
    return this.execute(url, HttpMethod.GET, requestCallback, responseExtractor, (Map)uriVariables);
  }
  public <T> T getForObject(URI url, Class<T> responseType) throws RestClientException {
       ***
    return this.execute(url, HttpMethod.GET, requestCallback, responseExtractor);
  }`
  getForEntity():
  `public <T> ResponseEntity<T> getForEntity(String url, Class<T> responseType, Object... uriVariables) throws RestClientException {
       ***
    return (ResponseEntity)nonNull(this.execute(url, HttpMethod.GET, requestCallback, responseExtractor, uriVariables));
  }
    public <T> ResponseEntity<T> getForEntity(String url, Class<T> responseType, Map<String, ?> uriVariables) throws RestClientException {
       ***
    return (ResponseEntity)nonNull(this.execute(url, HttpMethod.GET, requestCallback, responseExtractor, uriVariables));
   }
    public <T> ResponseEntity<T> getForEntity(URI url, Class<T> responseType) throws RestClientException {
       ***
    return (ResponseEntity)nonNull(this.execute(url, HttpMethod.GET, requestCallback, responseExtractor));
}``
以上是RestTemplate中发送get 请求调用Http客户端方法的方法;
   String forObject = restTemplate.getForObject(verifyUrl, String.class);
   ResponseEntity<String> forEntity = restTemplate.getForEntity(verifyUrl, String.class);
   getForEntity比getForObject :getForEntity 是将返回的结果封装在ResponseEntity 响应实体中, getForObject是将结果按照指定的返回值类型返回;
   总之(一句话):getForEntity()相当于将 getForObject() 方法的结果封装成了
1.3.2 post请求
1.3.3 post请求
1.3.4 post请求

posted on 2020-09-29 15:39  夜空中闪闪发光的星星  阅读(193)  评论(0)    收藏  举报