`
v5qqbrowser
  • 浏览: 356304 次
文章分类
社区版块
存档分类
最新评论

Android网络编程之Http通信(cmwap处理)

 
阅读更多

先附上一个Demo的截图:

需要Demo的可以直接下载来看看:http://download.csdn.net/detail/shinay/4380308



在Android开发Http程序的时候,可以选择HttpURLConnection和HttpClient接口进行编程,下面就说下这两种方式的写法:

HttpURLConnection
get方式:

	/**
	 * 通过Get方式从网络获取数据
	 * @param urlString URL地址
	 */
	public static String getResultFromNetByGet() {
		String urlString = "http://suggestion.baidu.com/su?wd=a";
		StringBuffer sb = new StringBuffer();
		try {
			URL url = new URL(urlString);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod("GET"); // 设置请求方式为GET, 由于默认为GET, 所以这里可以省略
			/**
			 * 得到InputStream对象, 调用getInputStream会
			 * 自动去调用connect()方法, 因此前面我们可以不
			 * 用自己调connect()方法
			 */
			InputStream in = connection.getInputStream();
			/**
			 * 通过InputStream获取到Reader对象, 方便我们
			 * 读取数据, 并设置对应编码避免中文乱码问题
			 */
			InputStreamReader isr = new InputStreamReader(in, "GBK");
			BufferedReader reader = new BufferedReader(isr);
			String temp;
			while((temp = reader.readLine()) != null) {
				sb.append(temp);
			}
			in.close(); // 关闭InputStream
			connection.disconnect(); // 断开连接
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sb.toString();
	}

post方式:

	/**
	 * 通过Post方式从网络获取数据
	 * @param urlString URL地址
	 */
	public static String getResultFromNetByPost() {
		String urlString = "http://www.kd185.com/ems.php";
		String wen = "MS2201828";
        String btnSearch = "EMS快递查询";
		StringBuffer sb = new StringBuffer();
		URL url;
		try {
			url = new URL(urlString);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod("POST"); // 设置请求方式为POST
			// connection.setConnectTimeout(10000); // 连接超时 单位毫秒
	        // connection.setReadTimeout(2000); // 读取超时 单位毫秒
			connection.setDoOutput(true); // 是否输入参数
			StringBuffer params = new StringBuffer();
	        // 表单参数与get形式一样
			params.append("wen").append("=").append(wen).append("&")
            		.append("btnSearch").append("=").append(btnSearch);
	        byte[] bytes = params.toString().getBytes();
	        connection.getOutputStream().write(bytes); // 输入参数
	        
	        InputStream in = connection.getInputStream();
			InputStreamReader isr = new InputStreamReader(in, "GBK");
			BufferedReader reader = new BufferedReader(isr);
			String temp;
			while((temp = reader.readLine()) != null) {
				sb.append(temp);
			}
			in.close(); // 关闭InputStream
			connection.disconnect(); // 断开连接
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sb.toString();
	}


HttpClient
get方式:

        /**
	 * 通过Get方式从网络获取数据
	 * @param urlString URL地址
	 */
	public static String getResultFromNetByGet() {
		String urlString = "http://suggestion.baidu.com/su?wd=a";
		StringBuffer sb = new StringBuffer();
		try {
			// HttpGet连接对象  
			HttpGet httpRequest = new HttpGet(urlString);
			// 取得HttpClient对象  
			HttpClient httpclient = new DefaultHttpClient();
			// 请求HttpClient,取得HttpResponse  
			HttpResponse httpResponse;
			httpResponse = httpclient.execute(httpRequest);
			// 请求成功  
			if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {  
				// 取得返回的字符串  
				String strResult = EntityUtils.toString(httpResponse.getEntity());  
				sb.append(strResult);
			} else {  
				sb.append("请求错误!");
			}  
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}  
		return sb.toString();
	}

post方式:
	/**
	 * 通过Post方式从网络获取数据
	 * @param urlString URL地址
	 */
	public static String getResultFromNetByPost() {
		String urlString = "http://www.kd185.com/ems.php";
		String wen = "MS2201828";
        String btnSearch = "EMS快递查询";
		StringBuffer sb = new StringBuffer();
		try {
			// HttpPost连接对象  
			HttpPost httpRequest = new HttpPost(urlString);  
			// 使用NameValuePair来保存要传递的Post参数  
			List<NameValuePair> params = new ArrayList<NameValuePair>();  
			// 添加要传递的参数  
			params.add(new BasicNameValuePair("wen", wen));  
			params.add(new BasicNameValuePair("btnSearch", btnSearch));  
			// 设置字符集  
//			HttpEntity httpentity = new UrlEncodedFormEntity(params, "GBK");
			HttpEntity httpentity = new UrlEncodedFormEntity(params);
			// 请求httpRequest  
			httpRequest.setEntity(httpentity);  
			// 取得默认的HttpClient  
			HttpClient httpclient = new DefaultHttpClient();  
			// 取得HttpResponse  
			HttpResponse httpResponse = httpclient.execute(httpRequest);  
			// 请求成功  
			if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {  
				// 取得返回的字符串  
				String strResult = EntityUtils.toString(httpResponse.getEntity());  
				sb.append(new String(strResult.getBytes("iso8859_1"), "gbk"));
			} else {  
				sb.append("请求错误!");
			}  
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}  
		return sb.toString();
	}


访问网络需要如下权限

    <uses-permission android:name="android.permission.INTERNET"/>


注意:在Android手机上,如果网络设置为cmwap方式上网的话,在有些机子或者有些ROM中是无法正常访问的,因此在这种情况下,还要用代理的方式,下面就讲讲:

首先是判断当前网络是否为cmwap:

	/**
	 * 判断当前网络模式是否为CMWAP
	 * @param context
	 * @return
	 */
	public static boolean isCmwapNet(Context context) {
		ConnectivityManager manager = (ConnectivityManager) context
			.getSystemService(Context.CONNECTIVITY_SERVICE);  
		NetworkInfo netWrokInfo = manager.getActiveNetworkInfo();  
		if(netWrokInfo == null || !netWrokInfo.isAvailable()) { 
			return false;
		} else if (netWrokInfo.getTypeName().equals("mobile")
				&& netWrokInfo.getExtraInfo().equals("cmwap")){
			return true;
        }
		return false;
	}

当然还要加上需要权限
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>


对应的方法我就不说明了,直接列出:
	/**
	 * 通过Get方式从网络获取数据(网络模式为CMWAP)
	 * 需要使用代理
	 * @param urlString URL地址
	 */
	public static String getResultFromNetByGetAndCmwap() {
		String urlString = "http://10.0.0.172/su?wd=a";
		StringBuffer sb = new StringBuffer();
		try {
			URL url = new URL(urlString);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setRequestProperty("X-Online-Host", "suggestion.baidu.com");  
			connection.setRequestMethod("GET"); // 设置请求方式为GET, 由于默认为GET, 所以这里可以省略
			/**
			 * 得到InputStream对象, 调用getInputStream会
			 * 自动去调用connect()方法, 因此前面我们可以不
			 * 用自己调connect()方法
			 */
			InputStream in = connection.getInputStream();
			/**
			 * 通过InputStream获取到Reader对象, 方便我们
			 * 读取数据, 并设置对应编码避免中文乱码问题
			 */
			InputStreamReader isr = new InputStreamReader(in, "GBK");
			BufferedReader reader = new BufferedReader(isr);
			String temp;
			while((temp = reader.readLine()) != null) {
				sb.append(temp);
			}
			in.close(); // 关闭InputStream
			connection.disconnect(); // 断开连接
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sb.toString();
	}

	/**
	 * 通过Post方式从网络获取数据(网络模式为CMWAP)
	 * 需要使用代理
	 * @param urlString URL地址
	 */
	public static String getResultFromNetByPostAndCmwap() {
		String urlString = "http://10.0.0.172/ems.php";
		String wen = "MS2201828";
        String btnSearch = "EMS快递查询";
		StringBuffer sb = new StringBuffer();
		URL url;
		try {
			url = new URL(urlString);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setRequestProperty("X-Online-Host", "www.kd185.com");  
			connection.setRequestMethod("POST"); // 设置请求方式为POST
			// connection.setConnectTimeout(10000); // 连接超时 单位毫秒
	        // connection.setReadTimeout(2000); // 读取超时 单位毫秒
			connection.setDoOutput(true); // 是否输入参数
			StringBuffer params = new StringBuffer();
	        // 表单参数与get形式一样
			params.append("wen").append("=").append(wen).append("&")
            		.append("btnSearch").append("=").append(btnSearch);
	        byte[] bytes = params.toString().getBytes();
	        connection.getOutputStream().write(bytes); // 输入参数
	        
	        InputStream in = connection.getInputStream();
			InputStreamReader isr = new InputStreamReader(in);
			BufferedReader reader = new BufferedReader(isr);
			String temp;
			while((temp = reader.readLine()) != null) {
				sb.append(temp);
			}
			in.close(); // 关闭InputStream
			connection.disconnect(); // 断开连接
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sb.toString();
	}

	/**
	 * 通过Get方式从网络获取数据(网络模式为CMWAP)
	 * 需要使用代理
	 * @param urlString URL地址
	 */
	public static String getResultFromNetByGetAndCmwap() {
		String urlString = "/su?wd=a";
		StringBuffer sb = new StringBuffer();
		try {
			HttpHost proxy = new HttpHost("10.0.0.172", 80, "http");
			HttpHost target = new HttpHost("suggestion.baidu.com", 80, "http");
			// HttpGet连接对象  
			HttpGet httpRequest = new HttpGet(urlString);
			// 取得HttpClient对象  
			HttpClient httpclient = new DefaultHttpClient();
			httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
			// 请求HttpClient,取得HttpResponse  
			HttpResponse httpResponse;
			httpResponse = httpclient.execute(target, httpRequest);
			// 请求成功  
			if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {  
				// 取得返回的字符串  
				String strResult = EntityUtils.toString(httpResponse.getEntity());  
				sb.append(strResult);
			} else {  
				sb.append("请求错误!");
			}  
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}  
		return sb.toString();
	}

	/**
	 * 通过Post方式从网络获取数据(网络模式为CMWAP)
	 * 需要使用代理
	 * @param urlString URL地址
	 */
	public static String getResultFromNetByPostAndCmwap() {
		String urlString = "/ems.php";
		String wen = "MS2201828";
        String btnSearch = "EMS快递查询";
		StringBuffer sb = new StringBuffer();
		try {
			HttpHost proxy = new HttpHost("10.0.0.172", 80, "http");
			HttpHost target = new HttpHost("www.kd185.com", 80, "http");
			
			// HttpPost连接对象  
			HttpPost httpRequest = new HttpPost(urlString);  
			// 使用NameValuePair来保存要传递的Post参数  
			List<NameValuePair> params = new ArrayList<NameValuePair>();  
			// 添加要传递的参数  
			params.add(new BasicNameValuePair("wen", wen));  
			params.add(new BasicNameValuePair("btnSearch", btnSearch));  
			// 设置字符集  
//			HttpEntity httpentity = new UrlEncodedFormEntity(params, "GBK");
			HttpEntity httpentity = new UrlEncodedFormEntity(params);
			// 请求httpRequest  
			httpRequest.setEntity(httpentity);  
			// 取得默认的HttpClient  
			HttpClient httpclient = new DefaultHttpClient();  
			httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
			// 取得HttpResponse  
			HttpResponse httpResponse = httpclient.execute(target, httpRequest);  
			// 请求成功  
			if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {  
				// 取得返回的字符串  
				String strResult = EntityUtils.toString(httpResponse.getEntity());  
				//sb.append(new String(strResult.getBytes("iso8859_1"), "gbk"));
				sb.append(strResult);
			} else {  
				sb.append("请求错误!");
			}  
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}  
		return sb.toString();
	}

分享到:
评论

相关推荐

    Android网络Http通信(及cmwap处理)

    HttpURLConnection和HttpClient接口的get post访问 cmwap下代理

    AndroidHttp通信(及cmwap处理)

    android下的两种http访问方式 HttpURLConnection和HttpClient接口 以前在cmwap网络下代理访问

    Android_WIFI,CMWAP,CMNET的自动判断访问

    Android_WIFI,CMWAP,CMNET的自动判断访问 Android_WIFI,CMWAP,CMNET的自动判断访问 Android_WIFI,CMWAP,CMNET的自动判断访问 Android_WIFI,CMWAP,CMNET的自动判断访问

    Android手机怎么用CMWAP上网?.doc

    Android手机怎么用CMWAP上网?

    关于cmwap网络切换

    提供一个关于cmwap切换的Demo,首先判断设备的APN是否存在CMWAP,如果有,就选中。如没有,就通过程序添加一个cmwap。

    Android编程获取网络连接方式及判断手机卡所属运营商的方法

    本文实例讲述了Android编程获取网络连接方式及判断手机卡所属运营商的方法。分享给大家供大家参考,具体如下: 问题:项目中写的网络模块,感觉有点乱:两套代码 –模拟器、真机,维护起来十分麻烦。 解决办法:代码...

    AndroidWIFI,CMWAP,CMNET的自动判断访问.pdf

    AndroidWIFI,CMWAP,CMNET的自动判断访问.pdf

    cmwap代理软件

    cmwap代理软件

    Android手机设置cmwap上网

    Android 手机设置CMWAP 接入点  设置--- 无限控件---移动网络设置---接入点名称----再按菜单---选择新apn  步,设置CMNET 上网APN  新建 APN  1.名称:cmnet  2.APN:cmnet  3.APN 类型:default  就只...

    Android开发之获取网络链接状态

    网络开发是Android程序设计一个非常重要的内容,今天本文就和大家一起分享一下Android网络开发的一点经验。 本文主要通过实例形式说明了Android获取网络链接状态的方法。具体内容如下: 就目前的Android手机来说,...

    CMWAP配置描述文件

    CMWAP配置描述文件

    android APN 设置

    在android代码中切换网络,如cmnet,cmwap

    cmwap配置文件

    移动无线流量卡的福音proxifier 的cmwap代理文件

    动感大挪移(cmwap代理)

    CMWAP是要设置代理才能上的 HTTP代理设置为10.0.0.172 端口:80 推荐用动感挪移这个代理软件,基本上可以使CMWAP当作CMNET来用!

    Android操作介绍

    android系统介绍 给android手机设置WIFI无线网络 关于CMWAP,CMNET,GPRS,EDGE问题集合 android手机如何用CMWAP上网? 什么是APK文件?它和android手机是什么关系?

    j2me自动连接网络,可以是cmwap或者cmnet

    J2ME自动获取网络连接的方法,非常智能,而且代码编写很好。

    基础电子中的Android手机设置cmwap上网

    Android 手机设置CMWAP 接入点  设置--- 无限控件---移动网络设置---接入点名称----再按菜单---选择新apn  第一步,设置CMNET 上网APN  新建 APN  1.名称:cmnet  2.APN:cmnet  3.APN 类型:default  ...

    cmwap转cmnet

    早期用GPRS写的程序,C2C.exe可以实现劲舞团,魔兽世界等TCP协议的程序通过cmwap游戏。cmwap.exe可以使qq通过cmwap上网时不会掉线。根据地方不同,cmwap可能会有不同情况,有的地方限制严格,cmwap.exe不一定有用。...

    Android应用源码YiBo聚合微博客户端

    支持3G、WIFI、CMNET和CMWAP等各种网络类型接入; 使用OAuth认证方式,保护帐号和通信安全 不过比较遗憾的是项目团队已经解散,不再进行任何官方的版本更新和Bug修复。官网网址yibo.me项目编码UTF-8默认编译版本...

Global site tag (gtag.js) - Google Analytics