我正在使用Java1.7。
当我在Firefox中用Postman测试请求时,我得到了一个响应状态: 200,Json响应很好。
当我用我的Java应用程序测试它时,我得到了这个异常:
java.net.ProtocolException:服务器重定向太多次(20次)
以下是我的java代码:
try{
String charset = "UTF-8";
URL url = new URL("http://example.com/ws");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Accept-Charset", charset);
con.setRequestProperty("token", "mytokenvalue");
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
}catch(Exception ex){
ex.printStackTrace();
}在这一行中抛出异常:
int responseCode = con.getResponseCode();发布于 2018-10-03 13:21:45
必须在打开连接之前设置此属性:
HttpURLConnection.setFollowRedirects(false);
https://stackoverflow.com/questions/40972116
复制相似问题