android為HttpClient和HttpURLConnection添加中國移動代理

fmms 12年前發布 | 40K 次閱讀 Android開發 移動開發 Android

     在android中,一般需要聯網的時候前,都要做一次網絡的判斷,判斷當前的網絡狀態!然后開始請求網絡

     當我們使用wap網絡的時候,程序中必須要中國移動代理!這樣的話,手機才能正常的訪問internet!

     在android中,有兩種方式請求網絡:HttpURLConnection和HttpClient請求方式,如果網絡狀態為wap的時候,都要為兩種請求添加中國移動代理的!
     第一種方式:HttpURLConnection
    /**
     * @author spring sky
     * Email vipa1888@163.com
     * QQ:840950105 My name:石明政
     * 使用HttpURLConnection請求Internet
     * @param context   context對象
     * @param requestUrl  請求的URL
     * @param param   請求的參數
     * @return  返回一個inputstream流
     */
    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{
&nbsp;&nbsp;&nbsp;              &nbsp;conn = url.openConnection();
&nbsp;&nbsp;            }           
                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

   /**
     * @author spring sky
     * Email vipa1888@163.com
     * QQ:840950105 My name :石明政
     * 使用HttpURLConnection請求Internet
     * @param context   context對象
     * @param requestUrl  請求的URL
     * @param param   請求的參數
     * @return  返回一個inputstream流
     */
    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在上網請求的時候,存在很多問題的(我是深有體會的,比如請求無響應,信號不好都可能造成一些未知的錯誤)

     好了,熟悉掌握了兩種請求方式了,android的聯網應用就可以開發了!

 本文由用戶 fmms 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!