论述Android通过HttpURLConnection与HttpClient联网代理网关设置

 Android联网主要使用HttpURLConneciton和HttpClient进行联网,在手机联网的时候,我们优先选择wifi网络,其次在选择移动网络,这里所述移动网络主要指cmwap。

大家都知道cmwap连接需要设置代理地址和端口,那么,android程序中如何设置代理呢?这是个问题。

HttpURLConnection设置代理

1 //当我们使用的是中国移动的手机网络时,下面方法可以直接获取得到10.0.0.172,80端口  
2 String host=android.net.Proxy.getDefaultHost();//通过andorid.net.Proxy可以获取默认的代理地址  
3 int port =android.net.Proxy.getDefaultPort();//通过andorid.net.Proxy可以获取默认的代理端口  
4 SocketAddress sa=new InetSocketAddress(host,port);  
5 //定义代理,此处的Proxy是源自java.net  
6 Proxy proxy=new Proxy(java.net.Proxy.Type.HTTP,sa);  
7 URL getUrl = new URL(“www.baidu.com”);   
8 HttpURLConnection con = (HttpURLConnection) getUrl.openConnection(proxy);//设置代理 

HttpClient设置代理

1 DefaultHttpClient httpClient=new DefaultHttpClient();  
2 String host=Proxy.getDefaultHost();//此处Proxy源自android.net  
3 int port = Proxy.getPort(context);//同上  
4 HttpHost httpHost = new HttpHost(host, port);   
5 //设置代理  
6 httpClient.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY,httpHost);  
7 HttpGet httpGet=new HttpPost("<a href="http://www.baidu.com">www.baidu.com</a>");  
8 HttpResponse response=httpClient.execute(httpGet);  

第一种方式:通过HttpURLConnection来访问

 public static InputStream getHttpURLConnectionInputStream(Context context,String requestUrl,Map<String, String> param) {  
          
        URL url;  
        HttpURLConnection conn = null;  
        InputStream input = null;  
        try {  
            url = new URL(requestUrl);  
            if(getAPNType(context)==NetWorkUtil.CMWAP)   //当请求的网络为wap的时候,就需要添加中国移动代理  
            {  
                Proxy proxy = new Proxy(java.net.Proxy.Type.HTTP,new InetSocketAddress("10.0.0.172", 80));  
                conn = (HttpURLConnection) url.openConnection(proxy);  
            }else{  
                  conn = url.openConnection();  
              }             
                conn.setConnectTimeout(10000);    //请求超时  
                conn.setRequestMethod("POST");  //请求方式  
                conn.setReadTimeout(1000);   //读取超时  
                conn.setDoOutput(true);  
                conn.setDoInput(true);  
                conn.setUseCaches(false);  
                conn.setRequestProperty("Charset", "UTF-8");  
                conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");  
                OutputStream os = conn.getOutputStream();      
                StringBuilder sb = new StringBuilder();  
                Iterator<String> it = param.keySet().iterator();  
                while (it.hasNext()) {  
                    String key = it.next();  
                    String value = param.get(key);  
                    sb.append(key).append("=").append(value).append("&");  
                }  
                String p = sb.toString().substring(0, sb.length()-1);  
                System.out.println("请求的参数"+p);  
                os.write(p.getBytes("utf-8"));  
                os.close();  
                if(conn!=null)  
                {  
                    input = conn.getInputStream();  
                }  
              
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return input;  
    }  

上面这种方式就是HttpURLConnection ,这种方式在android开发中也是比较常用的,希望朋友们也要熟悉的掌握!

 第二种方式:HttpClient

public static InputStream getHttpClientInputStream(Context context,String requestUrl, Map<String, String> param)throws Exception {  
    HttpClient client = new DefaultHttpClient();  
    if(getAPNType(context)==NetWorkUtil.CMWAP)  //当请求的网络为wap的时候,就需要添加中国移动代理  
    {   
        HttpHost proxy = new HttpHost("10.0.0.172", 80);  
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,  
                proxy);  
    }  
    HttpPost hp = new HttpPost(requestUrl);  
    hp.setHeader("Charset", "UTF-8");  
    hp.setHeader("Content-Type", "application/x-www-form-urlencoded");  
    List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();  
      
    Iterator<String> it = param.keySet().iterator();  
    while (it.hasNext()) {  
        String key = it.next();  
        list.add(new BasicNameValuePair(key, param.get(key)));  
    }  
    hp.setEntity(new UrlEncodedFormEntity(list,"UTF-8"));  
    HttpResponse response = null;  
    response = client.execute(hp);  
    return response.getEntity().getContent();  
}  

这个httpClient实现了android内置的DefaultHttpClient,所以使用起来还是很方便的!

但是我发现HttpClient 比HttpURLConnection 要好一些,因为HttpURLConnection 如果使用wap在上网请求的时候,存在很多问题的(我是深有体会的,比如请求无响应,信号不好都可能造成一些未知的错误).

 

 

posted on 2014-03-05 11:30  laozhu1124  阅读(8999)  评论(1编辑  收藏  举报

淘宝免费计数器