问题描述
我正在调用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?
推荐答案
方法将执行URL编码.
RestTemplate
methods that accept a String
URL perform URL encoding.
大概您已经提供了以下 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
.
根据文档建议
而不是使用接受 String
URL的重载,而是自己构造一个URI并使用它.
instead of using overloads that accept a String
URL, construct a URI yourself and use that.
Apache的 HttpComponents Fluent API 未指定行为,但似乎String值是按原样使用的.
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之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!