HttpURLConnection碰到连续302跳转的问题
用HttpURLConnection联网的代码:
HttpURLConnection conn = null;
URL url = new URL("http://10.0.0.172/");
conn = (HttpURLConnection) url.openConnection();
conn .setRequestMethod("POST");
conn .setDoInput(true);
conn .setDoOutput(true);
conn.setRequestProperty("X-Online-Host","www.xxxx.com");
conn.setConnectTimeout(30000); // 30秒超时
conn.connect();
如果返回的页面是一个302跳转,会自动跳转,但是如果跳转过去后还是一个302跳转,就卡在connect()这里了,超时之后一个 connection reset 的 exception. 不论Get还是Post方法,都一样问题。用setFollowRedirects关掉自动重定向,还是connection reset. 查了很长时间,还是弄不出个所以然来,看HttpURLConnection 的实现代码,redirect大于4次才会抛出一个Too many redirects 的异常,这才两个302就挂了...最后换用org.apache.http包里的东西,就没有问题。
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpHost proxy = new HttpHost("10.0.0.172", 80);
httpClient.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY,proxy);
HttpConnectionParams.setConnectionTimeout(httpClient.getParams(),20 * 1000);
HttpConnectionParams.setSoTimeout(httpClient.getParams(), 20 * 1000);
HttpGet httpget = new HttpGet(theurl);
HttpResponse response = httpClient.execute(httpget);
无论是自动跳转还是手动处理跳转都没有问题
作者 liujian885
补充:移动开发 , Android ,