首页 > 代码库 > Android万能使用WebServices(不用引入外部包)

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

直接上代码

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 =http://www.mamicode.com/ 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(不用引入外部包)