你的分享就是我们的动力 ---﹥

Android客户端添加代理访问网络

时间:2013-06-14 15:30来源:www.chengxuyuans.com 点击:

代码简介

因为公司的网络必须要通过代理才能访问外网, 给开发带了极大的不便。总共有两种一中是使用java自带的HttpURLConnection还有一种是使用Android平台中已经继承了的HttpClient

代码片段

private HttpClient client = null;
	private String url = PropertiesUtil.getUrl();
	private Gson gson;
	
	public RestTemplate () {
		HttpParams httpParams = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(httpParams, 50 * 1000);
		HttpConnectionParams.setSoTimeout(httpParams, 20 * 1000);
                HttpHost proxy = new HttpHost("10.50.0.100", 8080, "http");
		client = new DefaultHttpClient(httpParams);
                client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
		gson = new Gson();
}

代码片段

URL url = new URL(strUrl);
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("10.50.0.100",8080));
HttpURLConnection conn=(HttpURLConnection) url.openConnection(proxy); 
conn.setUseCaches(false);
conn.setRequestMethod(METHOD_GET);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setReadTimeout(READ_TIMEOUT);

转载注明地址:http://www.chengxuyuans.com/code/android/64578.html