Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android:調用webservice詳解;

Android:調用webservice詳解;

編輯:關於Android編程

很多時候要用到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.csdn.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
			
			
			
			  
			    
			      string
			       
			    
			  
			
		 */
		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;
	}
	

}


  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved