我应该在HttpURLConnection
项目中使用Spring
还是更好地使用RestTemplate
?
换句话说,什么时候最好使用每个?
答案 0 :(得分:4)
HttpURLConnection
和RestTemplate
是不同种类的野兽。它们在不同的抽象级别上运行。
RestTemplate
帮助使用REST
api,而HttpURLConnection
与HTTP协议兼容。
您在问什么是更好的使用。答案取决于您要实现的目标:
REST
API,请坚持使用RestTemplate
HttpURLConnection
OkHttpClient
,Apache的HttpClient
,或者如果您使用的是Java 11,则可以尝试其HttpClient
。此外,RestTemplate
使用HttpUrlConnection
/ OkHttpClient
/ ...来执行其工作(请参见ClientHttpRequestFactory
,SimpleClientHttpRequestFactory
,OkHttp3ClientHttpRequestFactory
< / 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是苦行僧。
您始终必须处理“低级” InputStream
,Reader
,OutputStream
,Writer
,但幸运的是,还有其他选择。
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);
}
容易得多,对吧?
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
HttpClient
。也值得一提: