android通过webservice连接SQL数据库(二)客户端
? ? ? ? ? 上文寫好了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 中:
我們所要做的就是獲取有用的數據,(藍色字體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) {ArrayListstrings=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){ArrayListstrings=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、不能再主線程中訪問網絡,訪問網絡需要開啟新的線程??梢杂肏andle類來完成主線程與子線程之間的交流。
? 參考:http://blog.csdn.net/zhyl8157121/article/details/8169172;
總結
以上是生活随笔為你收集整理的android通过webservice连接SQL数据库(二)客户端的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: android通过webservice连
- 下一篇: Android studio百度地图的使