照着视频编写了GetGoogle类,但是日文可以正常返回,中文就不行了,然后我把“http://www.google.com”换成“http://www.baidu.com”就没问题。
[code=java]import java.net.*;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.io.*;
public class GetGoogle {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
System.out.println("获取日文页面");
getContentByLanguage("ja");
System.out.println("\n");
System.out.println("获取中文页面");
getContentByLanguage("zh-cn");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void getContentByLanguage(String country) throws Exception{
URL urlGoogle = new URL("http://www.google.com");
HttpURLConnection googleConnection = (HttpURLConnection)urlGoogle.openConnection();
googleConnection.setRequestProperty("Accept-Language",country);
Map requests = googleConnection.getRequestProperties();
Set reqField = requests.keySet();
Iterator itrReq = reqField.iterator();
while(itrReq.hasNext()){
String field = (String) itrReq.next();
System.out.println(field + ":" +
googleConnection.getRequestProperty(field));
}
Map responses = googleConnection.getHeaderFields();
Set resFields = responses.keySet();
Iterator itrRes = resFields.iterator();
while(itrRes.hasNext()){
String field = (String) itrRes.next();
System.out.println(field + ":" +
googleConnection.getHeaderField(field));
}
InputStream is = googleConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String strLine = null;
while((strLine = br.readLine()) != null){
System.out.println(strLine);
}
br.close();
googleConnection.disconnect();
}
}[/code]
错误信息如下:
获取中文页面
Accept-Language:zh-cn
java.net.ProtocolException: Server redirected too many times (20)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection$6.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at sun.net.www.protocol.http.HttpURLConnection.getChainedException(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at GetGoogle.getContentByLanguage(GetGoogle.java:48)
at GetGoogle.main(GetGoogle.java:17)
Caused by: java.net.ProtocolException: Server redirected too many times (20)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getHeaderFields(Unknown Source)
at GetGoogle.getContentByLanguage(GetGoogle.java:39)
... 1 more |