android通过webservice连接SQL数据库(二)客户端

时间:2022-08-13 16:15:06

          上文写好了Webservice并且可以通过自己写的接口成功操作SQLsever,接下来就要完成客户端与服务器端的交流,获取数据转化成XML文件传给客户端。要想让客户端与服务器端进行交流必须满足几个前提:

1、Webservice调试成功并且能访问数据库。

2、成功发布Webservice与本地IIS,并且能够在IIS上浏览网站

3、手机(同网络)能够访问网站。


AndroidStudio代码:HttpConnSoap

import java.io.IOException;
        import java.io.InputStream;
        import java.io.OutputStream;
        import java.net.HttpURLConnection;
        import java.net.URL;
        import java.util.ArrayList;

public class HttpConnSoap {
    public ArrayList<String> GetWebServre(String methodName, ArrayList<String> Parameters, ArrayList<String> ParValues) {
        ArrayList<String> Values = new ArrayList<String>();

        //ServerUrl是指webservice的url
        //10.0.2.2是让android模拟器访问本地(PC)服务器,不能写成127.0.0.1
        //11125是指端口号,即挂载到IIS上的时候开启的端口
        //Service1.asmx是指提供服务的页面
//        String ServerUrl = "http://192.168.43.202/TourismWeb/TourismService.asmx";
        String ServerUrl = "http://192.168.174.2/TourismWeb/TourismService.asmx";
        //String soapAction="http://tempuri.org/LongUserId1";
        String soapAction = "http://tempuri.org/" + methodName;
        //String data = "";
        String soap = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
                + "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
                + "<soap:Body />";
        String tps, vps, ts;
        String mreakString = "";

        mreakString = "<" + methodName + " xmlns=\"http://tempuri.org/\">";
        for (int i = 0; i < Parameters.size(); i++) {
            tps = Parameters.get(i).toString();
            //设置该方法的参数为.net webService中的参数名称
            vps = ParValues.get(i).toString();
            ts = "<" + tps + ">" + vps + "</" + tps + ">";
            mreakString = mreakString + ts;
        }
        mreakString = mreakString + "</" + methodName + ">";
        /*
        +"<HelloWorld xmlns=\"http://tempuri.org/\">"
        +"<x>string11661</x>"
        +"<SF1>string111</SF1>"
        + "</HelloWorld>"
        */
        String soap2 = "</soap:Envelope>";
        String requestData = soap + mreakString + soap2;
        //System.out.println(requestData);

        try {
            URL url = new URL(ServerUrl);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            byte[] bytes = requestData.getBytes("utf-8");
            con.setDoInput(true);
            con.setDoOutput(true);
            con.setUseCaches(false);
            con.setConnectTimeout(12000);// 设置超时时间
            con.setRequestMethod("POST");
            con.setRequestProperty("Content-Type", "text/xml;charset=utf-8");
            con.setRequestProperty("SOAPAction", soapAction);
            con.setRequestProperty("Content-Length", "" + bytes.length);
            OutputStream outStream = con.getOutputStream();
            outStream.write(bytes);
            outStream.flush();
            outStream.close();
            InputStream inStream = con.getInputStream();

            //data=parser(inStream);
            //System.out.print("11");
            Values = inputStreamtovaluelist(inStream, methodName);
            //System.out.println(Values.size());


        } catch (Exception e) {
            System.out.print("2221");

        }
        return Values;
    }

    public ArrayList<String> inputStreamtovaluelist(InputStream in, String MonthsName) throws IOException {
        StringBuffer out = new StringBuffer();
        String s1 = "";
        byte[] b = new byte[4096];
        ArrayList<String> Values = new ArrayList<String>();
        Values.clear();

        for (int n; (n = in.read(b)) != -1;) {
            s1 = new String(b, 0, n);
            out.append(s1);
        }

        System.out.println(out);
        String[] s13 = out.toString().split("><");
        String ifString = MonthsName + "Result";
        String TS = "";
        String vs = "";

        Boolean getValueBoolean = false;
        for (int i = 0; i < s13.length; i++) {
            TS = s13[i];

            System.out.println(TS);
            int j, k, l;
            j = TS.indexOf(ifString);
            k = TS.lastIndexOf(ifString);

            if (j >= 0) {
                System.out.println(j);
                if (getValueBoolean == false) {
                    getValueBoolean = true;
                } else {

                }

                if ((j >= 0) && (k > j)) {
                    System.out.println("FFF" + TS.lastIndexOf("/" + ifString));
                    //System.out.println(TS);
                    l = ifString.length() + 1;
                    vs = TS.substring(j + l, k - 2);
                    //System.out.println("fff"+vs);
                    Values.add(vs);
                    System.out.println("退出" + vs);
                    getValueBoolean = false;
                    return Values;
                }

            }
            if(TS.equals("string /")){
                Values.add(" "); continue;
            }
            if(TS.equals("string/")){
                Values.add(" "); continue;
            }
            if (TS.lastIndexOf("/" + ifString) >= 0) {
                getValueBoolean = false;
                return Values;
            }

            if ((getValueBoolean) && (TS.lastIndexOf("/" + ifString) < 0) && (j < 0)) {
                k = TS.length();
                //System.out.println(TS);
                vs = TS.substring(7, k - 8);
                //System.out.println("f"+vs);
                Values.add(vs);
            }

        }

        return Values;
    }

}

这个类可以直接用,作用就是把连接服务器,把WebService上写的函数的返回值转化为数组类型 ArraryList<String>。

参数说明: methodname:调用的函数名,这个就是要调用Webservice上的函数名

    parameters:数组,数组每个元素是对应函数的参数名,要求参数名一致。

    parValues:数组,数组每个元素是对应参数的值。

要改的地方只用一处,就是ServerUrl,根据自己Webservice的URL改动。

其中服务器返回的是如下字符串,存放在变量 out 中:

android通过webservice连接SQL数据库(二)客户端

我们所要做的就是获取有用的数据,(蓝色字体string会被替换成实际值),也就是   方法名+“Result” 标签   之间的数据。

通过字符串截取,将获取出来的数据存放在变量Values中并返回。但是不能成功获取复杂值。

使用HttpconnSoap的实例代码如下:

类2:DBUtil,使用

import java.io.IOException;
        import java.io.InputStream;
        import java.io.OutputStream;
        import java.net.HttpURLConnection;
        import java.net.URL;
        import java.util.ArrayList;

public class DBUtil {
    private ArrayList<String> arrayList = new ArrayList<String>();
    private ArrayList<String> brrayList = new ArrayList<String>();
    private ArrayList<String> crrayList = new ArrayList<String>();
    private HttpConnSoap Soap = new HttpConnSoap();
     //region  用户注册
    /**phonenum,name,sex,password,isguide*/
    public boolean insertUser(String phonenum, String name,String sex ,String  password,String address,String isguide) {
        ArrayList strings=new ArrayList();
        boolean flag=false;
        arrayList.clear();
        brrayList.clear();

        arrayList.add("phonenum");
        arrayList.add("name");
        arrayList.add("sex");
        arrayList.add("password");
        arrayList.add("address");
        arrayList.add("isguide");
        brrayList.add(phonenum);
        brrayList.add(name);
        brrayList.add(sex);
        brrayList.add(password);
        brrayList.add(address);
        brrayList.add(isguide);

        strings=Soap.GetWebServre("insertUser", arrayList, brrayList);
        if(strings.get(0)=="true");
        flag=true;
        return flag;
    }
    //endregion

    //region 账号密码是否匹配验证
    /**账号密码是否匹配验证,phonenum,password*/
    public  boolean IsMatchUser(String phonenum, String password)
    {
        ArrayList strings=new ArrayList();
        boolean flag=false;
        arrayList.clear();
        brrayList.clear();

        arrayList.add("phonenum");
        arrayList.add("password");
        brrayList.add(phonenum);
        brrayList.add(password);String a;
        strings= Soap.GetWebServre("IsMatchUser", arrayList, brrayList);
        if(strings!=null){
         a =strings.get(0);
        if(a.equals("true"))
            flag=true;
        }
        return flag;
    }
    //endregion
   /**根据phone找用户信息*/
    public List<HashMap<String, String>> SelectUserById (String phonenum){
        List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();

        arrayList.clear();
        brrayList.clear();
        crrayList.clear();
        arrayList.add("phonenum");
        brrayList.add(phonenum);
        crrayList = Soap.GetWebServre("SelectUserById", arrayList, brrayList);

        HashMap<String, String> tempHash = new HashMap<String, String>();
        tempHash.put("phoneNum", "phoneNum");
        tempHash.put("name", "name");
        tempHash.put("sex", "sex");
        tempHash.put("password", "password");
        tempHash.put("isguide", "isguide");
        tempHash.put("address", "address");
        tempHash.put("signature","signature");
        list.add(tempHash);

        for (int j = 0; j < crrayList.size(); j += 7) {
            HashMap<String, String> hashMap = new HashMap<String, String>();
            hashMap.put("phoneNum", crrayList.get(j));
            hashMap.put("name", crrayList.get(j + 1));
            hashMap.put("sex", crrayList.get(j + 2));
            hashMap.put("password", crrayList.get(j + 3));
            hashMap.put("isguide", crrayList.get(j + 4));
            hashMap.put("address",crrayList.get(j+5));
            hashMap.put("signature",crrayList.get(j+6));
            list.add(hashMap);
        }

        return list;
    }
}


成员: arrayList:存放调用函数的参数名

     brraryList:存放调用函数的参数值

     crraryList:存放服务器的返回值。

最后crraryList会把对应值存放在HashMap数组中。使用DBUtil类例子: new DBUtil().IsMatchUser( phonenum);


要注意的几点:

1、该类用到访问网络,所以要在AndroidManifest 添加访问网络的权限

<uses-permission android:name="android.permission.INTERNET"/>
2、不能再主线程中访问网络,访问网络需要开启新的线程。可以用Handle类来完成主线程与子线程之间的交流。


  参考:http://blog.csdn.net/zhyl8157121/article/details/8169172