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();
	}

 

  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值