- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我应该使用 HttpURLConnection
在 Spring
项目或者更好用RestTemplate
?换句话说,什么时候使用每个更好?
最佳答案
HttpURLConnection
和 RestTemplate
是不同种类的野兽。它们在不同的抽象级别上运行。
RestTemplate
有助于消耗 REST
API 和 HttpURLConnection
使用 HTTP 协议(protocol)。
您问的是用什么更好。答案取决于您想要实现的目标:
REST
api 然后坚持 RestTemplate
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
提供的 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:
Synchronous client to perform HTTP requests, exposing a simple, template method API over underlying HTTP client libraries such as the JDK {@code HttpURLConnection}, Apache HttpComponents, and others.
我们也做同样的事情
首先为了方便起见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<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);
}
<小时/>
所以回答你的问题:
When it is better to use each ?
REST
应用程序编程接口(interface)?使用RestTemplate
HttpClient
.还值得一提的是:
关于java - 我应该使用 HttpURLConnection 还是 RestTemplate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53795268/
我编写了以下代码来测试同步 RestTemplate 和 AsyncRestTemplate 的性能。我只是在 POSTMAN 上手动运行了几次。 我们只是将 10 个引用传递给 GET 调用,以便我
这种方式创建RestTemplate有什么区别 RestTemplate restTemplate = restTemplateBuilder .setConnectT
这个问题已经有答案了: IllegalArgumentException: Not enough variable values available with RestTemplate? (2 个回答
这是我的应用程序的主类 @SpringBootApplication (scanBasePackages = { "com.xyz.*" }) @EnableAsync @EnableAspectJA
我当前的代码: RestTemplate restTemplate = new RestTemplate(); restTemplate.getMessageConverters().add(new
我将开发一个简单的 Spring MVC Web 应用程序,它将使用 Heroku 上的远程 RESTful 服务。 我希望 MVC Web 应用程序根据 Controller 调用 REST 服务。
项目场景: Spring 的 RestTemplate 是一个健壮的、流行的基于 Java 的 Http客户端。 RestTemplate实现request param参数传送,如果如下所示,直接传一
我想通过 RestTemplate 发送请求。但是我的网址有大括号('{','}'),因此我有异常(exception):“没有足够的变量值可用于扩展......”。 我尝试通过 uri UriCom
有一个 RestFull 方法返回一个菜单对象列表 public ResponseEntity> getMenus() { .. } 但我不知道如何从 RestTemplate 中获取它们,从 Res
摘要: RestTemplate与REST资源交互的方法涵盖了HTTP请求方法,包括get, post, put, delete。 本文分享自华为云社区《Springboot RestTemplate
我有一个 springboot 休息服务 A 使用 restTemplate 调用休息服务 B。休息服务 A 的 restTemplate bean 创建如下,超时设置如下面的代码片段所示。 @Bea
我有一个 @Service有几种方法,每种方法使用不同的 web api。每个调用都应该有一个自定义的读取超时。 拥有一个 RestTemplate 实例并在每个方法中通过工厂更改超时是否是线程安全的
这是我的休息模板配置, @Bean @Qualifier("myRestService") public RestTemplate createRestTemplate(@Va
是否可以使用 RestTemplateBuilder 创建仅带有不记名 header 和 token 的 RestTemplate 实例? 我知道我可以使用 RestTemplate 交换并在 Htt
我正在尝试对请求正文执行 DELETE,但我不断收到 400(错误请求)错误。当我在 swagger/postman 中这样做时,它成功地删除了记录。但是从 Java 代码我不能这样做 外部 API
我需要创建 RestTemplate 请求,它将发送图像以通过 PHP 应用程序上传。 我的代码是: Resource resource = new FileSystemResource("/User
我正在使用 swagger codegen ( on this Zoura swagger ) 创建 Java/rest 模板客户端。我正在使用 swagger Gradle 插件: id "org.
我有Restful API,当找不到某个项目时会响应404错误,但是根据未找到该项目的原因(未知,不可用等),会有不同的消息,可以使用Spring MVC通过以下方式完成: response.send
我正在使用 Spring 中的 RestTemplate 来查询搜索服务。我在进行正确的序列化方面遇到了一些困难。如果我使用此方法,restTemplate 将返回一个列表。我不明白如何传递参数化类型
我们有这样的代码,它使用 OData 来指定资源(为简单起见,在此处使用公司代码进行硬编码): String uri = "[my_endpoint]/companyprofiles.read?$fi
我是一名优秀的程序员,十分优秀!