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("//www.baidu.com">www.baidu.com");  8 HttpResponse response=httpClient.execute(httpGet);  

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

 public static InputStream getHttpURLConnectionInputStream(Context context,String requestUrl,Map 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 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 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 list = new ArrayList();            Iterator 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在上网请求的时候,存在很多问题的(我是深有体会的,比如请求无响应,信号不好都可能造成一些未知的错误).

更多相关文章

  1. android 开机启动应用程序
  2. Android(安卓)ashmem的实现方式
  3. Android上传图片的方式
  4. Android实现监测网络变化以及无网络listview填充 简易新闻(十六
  5. Android(安卓)Codec 集成和 video Overlay
  6. 【Android】错误:Installation error: INSTALL_FAILED_VERSION_DO
  7. Android(安卓)Wifi锁之WifiLock
  8. android中显示网络图片
  9. Android数据存储方式(二)SharedPreferences(偏好参数保存)

随机推荐

  1. MySQL的GTID复制
  2. MySQL中SQL语句2
  3. mysql的级联复制和多源复制
  4. mysql的sql_mode设置
  5. MySQL-MHA集群部署(binlog复制)
  6. MySQL备份与恢复-mydumper
  7. 哪个同步盘最实用
  8. 哪个同步盘好一些
  9. Linux内存、Swap、Cache、Buffer详细解析
  10. 从键盘输入若干个学生成绩,输入负数作为输