问:怎样在Http连接中设置超时和代理?
Http连接的超时机制能够防止连接线程的无限期等待,一般可分为connect timeout和socket timeout,在Android中可以使用HttpClient和HttpURLConnection建立Http连接,因此存在两种设置超时的方式,首先Socket等待建立连接的超时时间和Socket输入流等待数据到达的超时时间设置如下:
private static final int HTTP_CONNECT_TIMEOUT = 20 * 1000; private static final int HTTP_SOCKET_TIMEOUT = 20 * 1000;
1)HttpClient方式
HttpClient httpClient = new DefaultHttpClient(); HttpParams params = httpClient.getParams(); HttpConnectionParams.setConnectionTimeout(params, HTTP_CONNECT_TIMEOUT); HttpConnectionParams.setSoTimeout(params, HTTP_SOCKET_TIMEOUT);
2)HttpURLConnection方式
try { URL url = new URL("http://www.baidu.com"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(HTTP_CONNECT_TIMEOUT); conn.setReadTimeout(HTTP_SOCKET_TIMEOUT); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }
Android应用程序访问互联网时,如果处于WIFI或者CMNET、UNINET或者3GNET,CTNET等接入方式时,无需设置代理即可顺利的访问网络,但是如果处于WAP环境下,那么就需要首先设置代理,之后才能访问互联网。Android通过WAP方式联网可参见http://blog.csdn.net/ace1985/article/details/7844159 跟设置超时一样,设置代理同样有HttpClient和HttpURLConnection两种方式:
1)HttpClient方式
HttpClient httpClient = new DefaultHttpClient(); String host = Proxy.getDefaultHost(); //默认代理服务器地址 int port = Proxy.getDefaultPort(); //默认代理服务器端口号 HttpHost httpHost = new HttpHost(host, port); HttpParams params = httpClient.getParams(); params.setParameter(ConnRouteParams.DEFAULT_PROXY, httpHost); //设置默认代理
1)HttpURLConnection方式
String host = android.net.Proxy.getDefaultHost(); // 默认代理服务器地址 int port = android.net.Proxy.getDefaultPort(); // 默认代理服务器端口号 SocketAddress socketAddr = new InetSocketAddress(host, port); // 构造代理对象 java.net.Proxy proxy = new java.net.Proxy(java.net.Proxy.Type.HTTP, socketAddr); try { URL url = new URL("www.baidu.com"); // 设置代理 HttpURLConnection conn = (HttpURLConnection) url.openConnection(proxy); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }