Android:调用webservice详解;

很多时候要用到android端调用webservice服务, 下面例子就是调用webservice 以及对流的多种方式处理;


package com.example.android_webservice;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.os.Bundle;

/**
 * 本例实现android端调用webservice,以及网络请求,以及流处理
 * 
 * @author andy
 * 
 * 其他内容请见http://blog.****.net/lyc66666666666
 */
public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_main);
		
		
		doPost();
		
	}

	
	private void doPost(){
		/**
		 * soap 1.2的完整请求 string替换成对应的城市和国家
		 * 
		 * POST /globalweather.asmx HTTP/1.1
			Host: www.webservicex.net
			Content-Type: application/soap+xml; charset=utf-8
			Content-Length: length
			
			<?xml version="1.0" encoding="utf-8"?>
			<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
			  <soap12:Body>
			    <GetWeather xmlns="http://www.webserviceX.NET">
			      <CityName>string</CityName>
			      <CountryName> </CountryName>
			    </GetWeather>
			  </soap12:Body>
			</soap12:Envelope>
		 */
		new Thread() {
			public void run() {
				try {
					
					/**
					 * ==================================================
					 * HttpURLConnection方式访问网络是最简单的实现,如果复杂的网络请求
					 * 比如带有session  cookie 长连接 或者更复杂的请求请用apache的开源项目httpclient来实现
					 * 
					 */
					
					
					InputStream is =  getXML(); //读取asset文件
					String requestContent = readStream(is);
					requestContent = setValue(requestContent, "beijing");//设置参数,查询北京的天气

					URL url = new URL("http://www.webservicex.net/globalweather.asmx"); 
					HttpURLConnection con = (HttpURLConnection) url.openConnection();
					
					con.setRequestMethod("POST");
					con.setReadTimeout(30000);
					con.setDoOutput(true);
					//下面的属性是根据soap协议的请求头设置的
					con.setRequestProperty("Content-Type", "application/soap+xml; charset=utf-8");
					con.setRequestProperty("Content-Length", String.valueOf(requestContent.getBytes().length));

					OutputStream os = con.getOutputStream();
					os.write(requestContent.getBytes());
					os.flush();
					os.close();
					
					if(con.getResponseCode()==200){
						InputStream instream = con.getInputStream();
						
						//以二进制流的方式读取输入流
						ByteArrayOutputStream byteOS = new ByteArrayOutputStream();
						int len = -1;
						byte[] buffer = new byte[1024];
						while (instream.read(buffer) != -1) {
							byteOS.write(buffer, 0, len);
						}
						
						System.out.println("返回的结果:"+new String(byteOS.toByteArray()));
					}
					
					
				} catch (Exception e) {
					e.printStackTrace();
				}
			};
		}.start();
	}
	
	
	/**
	 * 获取assets中的xml文件
	 * 
	 * @return
	 */
	private InputStream getXML() {
		
		InputStream inputstream;
		try {
			
			//获取xml文件的二进制流
			inputstream = this.getResources().getAssets().open("webservice.xml");
			return  inputstream;
			
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	
	/**
	 * 读取二进制流
	 * @param inputstream
	 * @return
	 */
	private String readStream(InputStream inputstream){
		try {

			InputStreamReader reader = new InputStreamReader(inputstream);
			BufferedReader bufferedReader = new BufferedReader(reader);

			StringBuffer sb = new StringBuffer();
			char[] buffer = new char[512];
			int length = bufferedReader.read(buffer);

			while (length != -1) {
				sb.append(new String(buffer));
				length = bufferedReader.read(buffer);
			}

			return sb.toString();

		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	
	
	/**
	 * 给xml的占位符填值
	 * @param xml
	 * @param value
	 * @return
	 */
	private String setValue(String xml, String value) {

		String result = null;
		//正则表达式,匹配$weather,然后进行替换
		Pattern pattern = Pattern.compile("\\$city");
		Matcher matcher = pattern.matcher(xml);
		if (matcher.find()) {
			result = matcher.replaceAll(value);
		}
		return result;
	}
	

}


Android:调用webservice详解;,布布扣,bubuko.com

Android:调用webservice详解;

上一篇:MindSpore手写数字识别初体验,深度学习也没那么神秘嘛


下一篇:java.lang.NoClassDefFoundError: org/apache/ibatis/mapping/DatabaseIdProvider