Jon Skeet说得对!
公共io代码:
String resultURL = String.format(GOOGLE_RECOGNIZER_URL, URLEncoder.encode("hello", "UTF-8"), "en-US");
URI uri = new URI(resultURL);
byte[] resultIO = IOUtils.toByteArray(uri);
我得到了这个例外:
Exception in thread "main" java.io.IOException: Server returned HTTP response code: 403 for URL: http://translate.google.cn/translate_tts?ie=UTF-8&q=hello&tl=en-US&total=1&idx=0&textlen=3
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1436)
at org.apache.commons.io.IOUtils.toByteArray(IOUtils.java:654)
at org.apache.commons.io.IOUtils.toByteArray(IOUtils.java:635)
at org.apache.commons.io.IOUtils.toByteArray(IOUtils.java:617)
at com.renren.intl.soundsns.simsimi.speech.ttsclient.impl.GoogleTTSClient.main(GoogleTTSClient.java:70)
但是当我使用httpclient时,结果是可以的。
String resultURL = String.format(GOOGLE_RECOGNIZER_URL, URLEncoder.encode(text, "UTF-8"), "en-US");
HttpClient client = new HttpClient();
GetMethod g = new GetMethod(resultURL);
client.executeMethod(g);
byte[] resultByte = g.getResponseBody();
这是怎么发生的?
提前感谢:)
maven依赖项:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
对我来说,在java.net.URL的情况下,JVM传递下一个标头:
User-Agent: Java/1.7.0_10
Host: translate.google.cn
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Connection: keep-alive
在Apache HttpClient:的情况下
User-Agent: Jakarta Commons-HttpClient/3.1
Host: translate.google.cn
如果更改,java.net.URL:的用户代理
System.setProperty("http.agent", "Jakarta Commons-HttpClient/3.1");
请求成功,没有HTTP 403。
如果您的用户代理以Java
开头,则似乎会收到403错误。任何具有模式Java.*
的用户代理都会抛出403错误。但如果你使用这个模式.+Java.*
,一切都可以。