Android:調用webservice詳解;

來源:互聯網
上載者:User

標籤:java   android   webserice   

很多時候要用到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 {@Overrideprotected 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.1Host: www.webservicex.netContent-Type: application/soap+xml; charset=utf-8Content-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;//Regex,匹配$weather,然後進行替換Pattern pattern = Pattern.compile("\\$city");Matcher matcher = pattern.matcher(xml);if (matcher.find()) {result = matcher.replaceAll(value);}return result;}}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.