Apache HTTP Client和Spring RestTemplate之间的区别 [英] Difference between Apache HTTP Client and Spring RestTemplate
问题描述
我正在调用Google Translate API,一个通过Apache HTTP Client调用,一个通过Spring的RestTemplate调用,并返回不同的结果.两者都获取完全相同的URL:
I'm making a call to the Google Translate API, one via Apache HTTP Client and one via Spring's RestTemplate, and getting different results back. Both are GETing exactly the same URL:
我想将"Professeur desécoles"从法语翻译成英语.
I want to translate "Professeur des écoles" from French to English.
使用的URL是(为了便于阅读,分为两行):
The URL used is (split onto two lines for sake of readability):
private static String URL = "https://www.googleapis.com/language/translate/v2?
key=AIzaSyBNv1lOS...&source=fr&target=en&q=Professeur+des+%C3%A9coles";
Apache:
@Test
public void apache() throws IOException {
String response = Request.Get(URL).execute().returnContent().asString();
System.out.println(response);
}
正确返回:
{数据": {翻译":[{"translatedText":学校老师" }]}}
{ "data": { "translations": [ { "translatedText": "School teacher" } ] } }
@Test
public void spring() {
RestTemplate template = new RestTemplate();
String response = template.getForObject(URL, String.class);
System.out.println(response);
}
返回(错误地):
{数据": {翻译":[{"translatedText":教授+ +%C3%A9coles" }]}}
{ "data": { "translations": [ { "translatedText": "Professor + of +% C3% A9coles" } ] } }
我在RestTemplate HTTP标头配置中缺少什么吗?
Am I missing something in RestTemplate HTTP header configuration?
推荐答案
RestTemplate
methods that accept a String
URL perform URL encoding.
对于每个HTTP方法,都有三种变体:两个接受URI模板字符串和URI变量(数组或映射),而三分之一接受URI.请注意,对于URI模板,假定编码为必要的,例如
restTemplate.getForObject("http://example.com/hotellist)
变成" http://example.com/hotel%20list"
.这也意味着如果URI模板或URI变量已被编码,双重编码将会发生,例如http://example.com/hotel%20list
变为http://example.com/hotel%2520list
).
大概您已经提供了以下 String
作为第一个参数
Presumably you've provided the following String
as the first argument
https://www.googleapis.com/language/translate/v2?key=MY_KEY&source=fr&target=en&q=Professeur+des+%C3%A9coles
必须对字符%
进行编码.因此,您的 q
参数的值变为
The character %
must be encoded. Your q
parameter's value therefore becomes
Professeur%2Bdes%2B%25C3%25A9coles
如果您解码,等同于
Professeur+des+%C3%A9coles
Google的翻译服务不知道如何处理%C3%A9coles
.
Google's translation services doesn't know what to do with %C3%A9coles
.
根据文档建议
为避免这种情况,请使用URI方法变体来提供(或重复使用)先前编码的URI.在完全控制的情况下准备这样的URI编码,请考虑使用
UriComponentsBuilder
.
而不是使用接受 String
URL的重载,而是自己构造一个URI并使用它.
instead of using overloads that accept a String
URL, construct a URI yourself and use that.
Apache's HttpComponents Fluent API does not specify the behavior but it seems the String value is taken as is.
这篇关于Apache HTTP Client和Spring RestTemplate之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!