热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

我应该使用HttpURLConnection还是RestTemplate

如何解决《我应该使用HttpURLConnection还是RestTemplate》经验,为你挑选了1个好方法。

我应该HttpURLConnectionSpring项目中使用还是更好地使用RestTemplate?换句话说,什么时候使用每个更好?



1> caco3..:

HttpURLConnectionRestTemplate不同种类的野兽。它们在不同的抽象级别上运行。

RestTemplate有助于消费RESTAPI和HttpURLConnection使用HTTP协议的工作。

您在问什么是更好的使用。答案取决于您要实现的目标:

如果您需要使用RESTapi,请坚持使用RestTemplate

如果你需要工作,http协议,然后使用HttpURLConnectionOkHttpClient,Apache的HttpClient,或者如果您使用的是Java 11你可以试试它HttpClient

此外,该RestTemplate应用HttpUrlConnection/ OkHttpClient/ ...做其工作(见ClientHttpRequestFactorySimpleClientHttpRequestFactoryOkHttp3ClientHttpRequestFactory


为什么不应该使用HttpURLConnection

最好显示一些代码:

在下面的示例中,使用了JSONPlaceholder

我们来GET个帖子:

public static void main(String[] args) {
  URL url;
  try {
    url = new URL("https://jsonplaceholder.typicode.com/posts/1");
  } catch (MalformedURLException e) {
    // Deal with it.
    throw new RuntimeException(e);
  }
  HttpURLConnection cOnnection= null;
  try {
    cOnnection= (HttpURLConnection) url.openConnection();
    try (InputStream inputStream = connection.getInputStream();
         InputStreamReader isr = new InputStreamReader(inputStream);
         BufferedReader bufferedReader = new BufferedReader(isr)) {
      // Wrap, wrap, wrap

      StringBuilder respOnse= new StringBuilder();
      String line;
      while ((line = bufferedReader.readLine()) != null) {
        response.append(line);
      }
      // Here is the response body
      System.out.println(response.toString());
    }

  } catch (IOException e) {
    throw new RuntimeException(e);
  } finally {
    if (connection != null) {
      connection.disconnect();
    }
  }
}

现在让我们POST发布一些内容:

cOnnection= (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-type", "application/json; charset=UTF-8");

try (OutputStream os = connection.getOutputStream();
     OutputStreamWriter osw = new OutputStreamWriter(os);
     BufferedWriter wr = new BufferedWriter(osw)) {
  wr.write("{\"title\":\"foo\", \"body\": \"bar\", \"userId\": 1}");
}

如果需要响应:

try (InputStream inputStream = connection.getInputStream();
     InputStreamReader isr = new InputStreamReader(inputStream);
     BufferedReader bufferedReader = new BufferedReader(isr)) {
  // Wrap, wrap, wrap

  StringBuilder respOnse= new StringBuilder();
  String line;
  while ((line = bufferedReader.readLine()) != null) {
    response.append(line);
  }

  System.out.println(response.toString());
}

如您所见,HttpURLConnectionis苦行僧提供了api 。

你总是要处理“低层次” InputStreamReaderOutputStreamWriter,幸好有替代品。


OkHttpClient

OkHttpClient减轻了疼痛:

GET张贴文章:

OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder()
    .url("https://jsonplaceholder.typicode.com/posts/1")
    .build();
Call call = okHttpClient.newCall(request);
try (Response respOnse= call.execute();
     ResponseBody body = response.body()) {

  String string = body.string();
  System.out.println(string);
} catch (IOException e) {
  throw new RuntimeException(e);
}

POST发帖:

Request request = new Request.Builder()
    .post(RequestBody.create(MediaType.parse("application/json; charset=UTF-8"),
        "{\"title\":\"foo\", \"body\": \"bar\", \"userId\": 1}"))
    .url("https://jsonplaceholder.typicode.com/posts")
    .build();

Call call = okHttpClient.newCall(request);

try (Response respOnse= call.execute();
     ResponseBody body = response.body()) {

  String string = body.string();
  System.out.println(string);
} catch (IOException e) {
  throw new RuntimeException(e);
}

容易得多,对吗?

Java 11的 HttpClient

GET张贴文章:

HttpClient httpClient = HttpClient.newHttpClient();

HttpResponse respOnse= httpClient.send(HttpRequest.newBuilder()
    .uri(URI.create("https://jsonplaceholder.typicode.com/posts/1"))
    .GET()
    .build(), HttpResponse.BodyHandlers.ofString());

System.out.println(response.body());

POST发帖:

HttpResponse respOnse= httpClient.send(HttpRequest.newBuilder()
    .header("Content-Type", "application/json; charset=UTF-8")
    .uri(URI.create("https://jsonplaceholder.typicode.com/posts"))
    .POST(HttpRequest.BodyPublishers.ofString("{\"title\":\"foo\", \"body\": \"barzz\", \"userId\": 2}"))
    .build(), HttpResponse.BodyHandlers.ofString());

RestTemplate

根据其javadoc:

同步客户端执行HTTP请求,在基础HTTP客户端库(如JDK {@code HttpURLConnection},Apache HttpComponents等)上公开简单的模板方法API。

让我们做同样的

首先,为方便起见,Post创建了类。(当RestTemplate读取响应时,它将转换为Post使用HttpMessageConverter

public static class Post {
  public long userId;
  public long id;
  public String title;
  public String body;

  @Override
  public String toString() {
    return new ReflectionToStringBuilder(this)
        .toString();
  }
}

GET婷一帖。

RestTemplate restTemplate = new RestTemplate();
ResponseEntity entity = restTemplate.getForEntity("https://jsonplaceholder.typicode.com/posts/1", Post.class);
Post post = entity.getBody();
System.out.println(post);

POST发帖:

public static class PostRequest {
  public String body;
  public String title;
  public long userId;
}

public static class CreatedPost {
  public String body;
  public String title;
  public long userId;
  public long id;

  @Override
  public String toString() {
    return new ReflectionToStringBuilder(this)
        .toString();
  }
}

public static void main(String[] args) {

  PostRequest postRequest = new PostRequest();
  postRequest.body = "bar";
  postRequest.title = "foo";
  postRequest.userId = 11;


  RestTemplate restTemplate = new RestTemplate();
  CreatedPost createdPost = restTemplate.postForObject("https://jsonplaceholder.typicode.com/posts/", postRequest, CreatedPost.class);
  System.out.println(createdPost);
}

因此,回答您的问题:

什么时候比较好使用?

需要使用RESTapi吗?使用RestTemplate

需要使用http吗?使用一些HttpClient


还值得一提:

Retrofit

简介 Feign

声明式REST客户端


推荐阅读
author-avatar
淘宝店名维衣潮都_233
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有