作者:淘宝店名维衣潮都_233 | 来源:互联网 | 2022-11-24 22:29
我应该HttpURLConnection
在Spring
项目中使用还是更好地使用RestTemplate
?换句话说,什么时候使用每个更好?
1> caco3..:
在HttpURLConnection
与RestTemplate
不同种类的野兽。它们在不同的抽象级别上运行。
将RestTemplate
有助于消费REST
API和HttpURLConnection
使用HTTP协议的工作。
您在问什么是更好的使用。答案取决于您要实现的目标:
如果您需要使用REST
api,请坚持使用RestTemplate
如果你需要工作,http协议,然后使用HttpURLConnection
,OkHttpClient
,Apache的HttpClient
,或者如果您使用的是Java 11你可以试试它HttpClient
。
此外,该RestTemplate
应用HttpUrlConnection
/ OkHttpClient
/ ...做其工作(见ClientHttpRequestFactory
,SimpleClientHttpRequestFactory
,OkHttp3ClientHttpRequestFactory
为什么不应该使用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
is苦行僧提供了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);
}
容易得多,对吗?
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);
}
因此,回答您的问题:
什么时候比较好使用?
需要使用REST
api吗?使用RestTemplate
需要使用http吗?使用一些HttpClient
。
还值得一提:
Retrofit
简介 Feign
声明式REST客户端