码迷,mamicode.com
首页 > 移动开发 > 详细

Android万能使用WebServices(不用引入外部包)

时间:2014-09-24 20:09:47      阅读:262      评论:0      收藏:0      [点我收藏+]

标签:android   style   blog   http   color   io   os   使用   java   

直接上代码

WebServicesLib.java

package com.example.testwebservices;

import java.io.InputStream;
import java.io.OutputStream;

import java.net.HttpURLConnection;
import java.net.URL;

import java.util.Map;

import org.xmlpull.v1.XmlPullParser;

import android.util.Xml;

//import javax.xml.parsers.DocumentBuilder;
//import javax.xml.parsers.DocumentBuilderFactory;
//
//import org.w3c.dom.Document;
//import org.w3c.dom.Element;
//import org.w3c.dom.NodeList;

public class WebServicesLib {

    /**
     * 调用WebServices
     *
     * @param SERVER_URL WebServices地址
     * @param serviceNameSpace WebServices命名空间
     * @param functionName 函数名
     * @param params 参数列表(名称必须对应)
     * @return 返回结果
     * @throws Exception
     */
    public static String InvokeWS(String SERVER_URL, String serviceNameSpace,    String functionName,  Map<String, String> params) throws Exception {
        StringBuffer strBuff = new StringBuffer();
        strBuff.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
        strBuff.append("<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\">\n");
        strBuff.append("  <soap12:Body>\n");
        if (params==null||params.size()==0) {
            strBuff.append("    <" + functionName + " xmlns=\""+ serviceNameSpace +"\" />\n");
        } else {
            strBuff.append("    <" + functionName + " xmlns=\""+ serviceNameSpace +"\">\n");
            for(Map.Entry<String, String> entry : params.entrySet())
            {
                strBuff.append("      <"+entry.getKey()+">" + entry.getValue() + "</"+entry.getKey()+">\n");
            }
            strBuff.append("    </" + functionName + ">\n");
        }

        strBuff.append("  </soap12:Body>\n");
        strBuff.append("</soap12:Envelope>");

//        return strBuff.toString();
        
        byte[] data = strBuff.toString().getBytes();
        // 提交Post请求
        URL url = new URL(SERVER_URL);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setConnectTimeout(5 * 1000);
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-Type","application/soap+xml; charset=utf-8");
        conn.setRequestProperty("Content-Length", String.valueOf(data.length));
        OutputStream outStream = conn.getOutputStream();
        outStream.write(data);
        outStream.flush();
        outStream.close();
        int responseCode = conn.getResponseCode();
        if (responseCode == 200) {
            InputStream inStream = conn.getInputStream();
            XmlPullParser parser = Xml.newPullParser();
            parser.setInput(inStream, "UTF-8");
            int eventType = parser.getEventType();// 产生第一个事件
            while (eventType != XmlPullParser.END_DOCUMENT) {
                // 只要不是文档结束事件
                switch (eventType) {
                case XmlPullParser.START_TAG:
                    String name = parser.getName();// 获取解析器当前指向的元素的名称
                    if ((functionName+"Result").equals(name)) {
                        return parser.nextText();
                    }
                    break;
                }
                eventType = parser.next();
            }
            return "";
        }
        return "Error:"+responseCode;
    }
}

调用方法

MainActivity.java

package com.example.testwebservices;

import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

    private TextView mobileAddress;

    private static final int MSG_SUCCESS = 0;// 
    private static final int MSG_FAILURE = 1;// 

    private Thread mThread;
    private boolean isRunning = false;
    /**
     * 异步调用
     */
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {// 此方法在UI线程运行
            switch (msg.what) {
            case MSG_SUCCESS:
                
                mobileAddress.setText(msg.obj.toString());
                Toast.makeText(getApplication(), "查询成功", Toast.LENGTH_LONG)
                        .show();
                break;
            case MSG_FAILURE:
                mobileAddress.setText(msg.obj.toString());
                Toast.makeText(getApplication(), "查询失败", Toast.LENGTH_LONG)
                        .show();
                break;
            }
            isRunning=false;
        }
    };

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            // 读取XML文件
            try {
                Map<String, String> params = new HashMap<String, String>();
                
                String add = WebServicesLib.InvokeWS(
                        "http://192.168.1.149:6666/WebServices/SystemRoles.asmx",
                        "http://tempuri.org/", "GetAllSystemRoles", params);
                mHandler.obtainMessage(MSG_SUCCESS, add).sendToTarget();
            } catch (Exception e) {
                mHandler.obtainMessage(MSG_FAILURE,e.getMessage()).sendToTarget();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        mobileAddress = (TextView) this.findViewById(R.id.mobileAddress);
        Button btnSearch = (Button) this.findViewById(R.id.btnSearch);
        btnSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // Android 4.0 之后不能在主线程中请求HTTP请求
                if (!isRunning) {
                    isRunning=true;
                    mThread = new Thread(runnable);
                    mThread.start();// 线程启动
                } else {
                    Toast.makeText(getApplication(), "线程已经启动。",Toast.LENGTH_LONG).show();
                }
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

}

 

Android万能使用WebServices(不用引入外部包)

标签:android   style   blog   http   color   io   os   使用   java   

原文地址:http://www.cnblogs.com/carbe/p/3991224.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!