我应该使用HttpURLConnection还是RestTemplate

时间:2018-12-15 16:55:44

标签: java spring

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

1 个答案:

答案 0 :(得分:4)

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

RestTemplate帮助使用REST api,而HttpURLConnection与HTTP协议兼容。

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

  • 如果您需要使用REST API,请坚持使用RestTemplate
  • 如果您需要使用http协议,请使用 HttpURLConnection OkHttpClient,Apache的HttpClient,或者如果您使用的是Java 11,则可以尝试其HttpClient

此外,RestTemplate使用HttpUrlConnection / OkHttpClient / ...来执行其工作(请参见ClientHttpRequestFactorySimpleClientHttpRequestFactoryOkHttp3ClientHttpRequestFactory < / p>


为什么不应该使用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());
}

您可以看到HttpURLConnection提供的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<String> 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<String> 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读取响应时,它将使用HttpMessageConverter将其转换为Post

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<Post> 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);
}

所以回答您的问题:

  

什么时候最好使用每个?

  • 需要使用REST API吗?使用RestTemplate
  • 需要使用http吗?使用一些HttpClient

也值得一提: