您的位置:首页 > 移动开发 > Android开发

安卓Web Service实现天气预报功能

2014-05-23 11:32 561 查看
Web Service是实现异构程序之间方法调用的一种机制。通过一种XML格式的特殊文件来描述方法、参数、调用和返回值,这种格式的XML文件称为WSDL(Web Service Description Language),即Web服务描述语言。Web Service采用的通信协议是SOAP,即简单对象访问协议。java领域的Web Service实现有多种方式。以下我们通过webService 调用 天气预报. 这里主要是讲解 如何调用webservice 返回的xml通过 pull解析 。UI界面只是用一个listView显示
pull解析后的字符串类型。可以用imageview显示的,这里 不在做界面的跳转。

调用网站 :http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx?op=getWeather

首先我们把请求SOAP 的 xml 放在项目中 然后使用$替换请求参数

weatcher.xml

<?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://WebXml.com.cn/">

      <theCityCode>$city</theCityCode>

      <theUserID></theUserID>

    </getWeather>

  </soap12:Body>

</soap12:Envelope>

main.xml:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:orientation="vertical"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent"

    >

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:orientation="horizontal"

    android:layout_width="fill_parent"

    android:layout_height="wrap_content"

    >

    <EditText

    android:id="@+id/edittext"

    android:layout_width="200dp"

    android:layout_height="wrap_content"

    />

    <Button

    android:layout_width="fill_parent"

    android:layout_height="wrap_content"

    android:id="@+id/btn"

    android:text="查询"

    />

    </LinearLayout>

<ListView 

    android:layout_width="fill_parent"

    android:layout_height="wrap_content"

    android:id="@+id/listview"

    />

</LinearLayout>

调用webservice,获取服务响应的数据,解析后并显示

public class DataAsyncLoadActivity extends Activity {

    /** Called when the activity is first created. */

        private ListView listView;

        private EditText editText;

        private Button btn;

    @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

         

       editText = (EditText) this.findViewById(R.id.edittext);

       btn = (Button) this.findViewById(R.id.btn);

       listView = (ListView) this.findViewById(R.id.listview);

        

       btn.setOnClickListener(new View.OnClickListener() {

                 

                @Override

                public void onClick(View v) {

                                // 读取xml文件

                         InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("weather.xml");

                         // 获取城市名称

                       String city = editText.getText().toString();

                         

                        try {

                                                List<String> lists;

                                                lists = getCityWeatch(inputStream, city);

                                        ArrayAdapter<String> adapter = new ArrayAdapter<String>(DataAsyncLoadActivity.this, 

                                                        android.R.layout.simple_list_item_1,lists);

                                        listView.setAdapter(adapter);

                        } catch (XmlPullParserException e) {

                                                // TODO Auto-generated catch block

                                                e.printStackTrace();

                                } catch (IOException e) {

                                        // TODO Auto-generated catch block

                                        e.printStackTrace();

                                        Toast.makeText(DataAsyncLoadActivity.this, "查询失败", 1).show();

                                }

                }

        });

        

    }

    /**

     * 获取 天气预报 

     * @param inputStream

     * @param city

     * @return

     * @throws IOException

     * @throws XmlPullParserException

     */

        private List<String> getCityWeatch(InputStream inputStream, String city) throws IOException, XmlPullParserException {

                // 将XML 中换成 城市名

                String soap = readSoapFile(inputStream, city);

                byte[] data = soap.getBytes();

                // 提交Post请求

                URL url = new URL("http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx");

                HttpURLConnection conn = (HttpURLConnection) url.openConnection();

                conn.setRequestMethod("POST");

                conn.setConnectTimeout(5000);

                conn.setDoOutput(true);

                conn.setRequestProperty("Content-Type", "application/soap+xml; charset=utf-8");        

                conn.setRequestProperty("Content-Length", String.valueOf(data.length));

                OutputStream out = conn.getOutputStream();

                out.write(data);

                out.flush();

                out.close();

                if(conn.getResponseCode() == 200){

                        // 解析返回信息

                        return parseResponseXML(conn.getInputStream());

                }

                 

                return null;

        }

        /**

         * 解析 XML 文件

         * @param inputStream

         * @return

         * @throws XmlPullParserException 

         * @throws IOException 

         */

        private List<String> parseResponseXML(InputStream inputStream) throws XmlPullParserException, IOException {

                XmlPullParser xmlPullParser = Xml.newPullParser();

                xmlPullParser.setInput(inputStream, "UTF-8");

                int event = xmlPullParser.getEventType();

                List<String> lists = new ArrayList<String>();

                String str = null;

                while(event != XmlPullParser.END_DOCUMENT){

                        switch (event) {

                        case XmlPullParser.START_TAG:

                                // 获取解析器当前指向的元素的名称

                                 

                                if("string".equals(xmlPullParser.getName()) ){

                                        str = xmlPullParser.nextText();

                                }

                                 

                                break;

                        case XmlPullParser.END_TAG:

                                if("string".equals(xmlPullParser.getName())){

                                        lists.add(str);

                                        str = null;

                                }

                                break;

                        }

                        event = xmlPullParser.next();

                }

                return lists;

        }

        private String readSoapFile(InputStream inputStream, String city) throws IOException {

                // TODO Auto-generated method stub

                // 从流中获取文件信息

                byte[] data = readInputStream(inpu
9d7e
tStream);

                String soapxml = new String(data);

                  // 占位符参数

                Map<String, String> params = new HashMap<String, String>();

                params.put("city", city);

                 // 替换文件中占位符

                return replace(soapxml, params);

        }

        /**

         * 替换 文件中的 占位符

         * @param soapxml

         * @param params

         * @return

         */

        private String replace(String soapxml, Map<String, String> params) {

                String result = soapxml;

                if(params != null && !params.isEmpty()){

                        for(Map.Entry<String, String> entry : params.entrySet()){

                                String name = "\\$" + entry.getKey();

                                Pattern pattern = Pattern.compile(name);

                                Matcher matcher = pattern.matcher(result);

                                if(matcher.find()){

                                        result = matcher.replaceAll(entry.getValue()); 

                                }

                        }

                }

                return result;

        }

        /**

         * 读取流信息

         * @param inputStream

         * @return

         * @throws IOException

         */

        private byte[]  readInputStream(InputStream inputStream) throws IOException {

                byte[] buf = new byte[1024];

                int len = -1;

                ByteArrayOutputStream out = new ByteArrayOutputStream();

                while((len = inputStream.read(buf)) != -1){

                        out.write(buf,0,len);

                }

                out.close();

                inputStream.close();

                return out.toByteArray();

        }

}

网络权限:

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

对了 这里 是 SOAP 响应xml 根据这个 使用的pull 解析数据

<?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>

    <getWeatherResponse xmlns="http://WebXml.com.cn/">

      <getWeatherResult>

        <string>string</string>

        <string>string</string>

      </getWeatherResult>

    </getWeatherResponse>

  </soap12:Body>

</soap12:Envelope>

关于运行效果这里不做展示,想看到结果那么可以自己动手去敲一遍代码,自己运行下,相信实践过比看过要熟悉很多,俗话说:好记性不如烂笔头。在学软件开发的过程中尤其要注重实践过程,从现在开始吧。时间有限,更多内容还请移步到上海android培训机构吧。本文由龙月整合营销专业于默认点评,大众点评网星级,专业社会化媒体整合营销。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息