Android平台调用WebService

Android平台调用WebServiceAndroid平台调用WebServiceAndroid平台调用WebService最近项目需要用到Android,连数据库,花了几天研究


参考了几篇博文,进行改进

因为很多博文写的时间已经很长了,现在Android版本升级,用不了

1.http://blog.****.net/zhyl8157121/article/details/8169172  这篇感觉挺经典的,有源代码可以下载

2.http://blog.****.net/lyq8479/article/details/6428288/  

3.http://blog.****.net/qq_32400847/article/details/52846561 

非常感谢前辈的贡献



总共三个类,数据操作类


一:Activity类

package User.User.namespace;


import User.User.namespace.DBUtil;
import User.User.namespace.R;


import android.os.Bundle;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.app.Dialog;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.os.StrictMode; 


public class UserListActivity extends Activity {
    /** Called when the activity is first created. */
 private Button btn1;
 private Button btn2;
 private Button btn3;
 private ListView listView;
 private SimpleAdapter adapter;
 private DBUtil dbUtil;
 List<HashMap<String,String>> list=new ArrayList<HashMap<String,String>>();
 
 
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn1 = (Button) findViewById(R.id.btn_all);
  btn2 = (Button) findViewById(R.id.btn_add);
  btn3 = (Button) findViewById(R.id.btn_delete);
  listView = (ListView) findViewById(R.id.listView);
  dbUtil = new DBUtil();
  
  btn1.setOnClickListener(new OnClickListener() {
   
   
   public void onClick(View v) {
    hideButton(true);
    setListView();
   }
  });

  btn2.setOnClickListener(new OnClickListener() {
   
 
   public void onClick(View v) {
    hideButton(true);
    setAddDialog();
   }
  });

  btn3.setOnClickListener(new OnClickListener() {
   

   public void onClick(View v) {
    hideButton(true);
    setDeleteDialog();
   }
  });
 }

 /**
  * 删除帐户信息
  */
   
 private void setDeleteDialog() {
  
  final Dialog dialog = new Dialog(UserListActivity.this);
  dialog.setContentView(R.layout.dialog_delete);
  dialog.setTitle("删除信息");
  Window dialogWindow = dialog.getWindow();
  WindowManager.LayoutParams lp = dialogWindow.getAttributes();
  dialogWindow.setGravity(Gravity.CENTER);
  dialogWindow.setAttributes(lp);

  final EditText cNoEditText = (EditText) dialog.findViewById(R.id.editText1);
  Button btnConfirm = (Button) dialog.findViewById(R.id.button1);
  Button btnCancel = (Button) dialog.findViewById(R.id.button2);

  btnConfirm.setOnClickListener(new OnClickListener() {


   public void onClick(View v) {
    //StrictMode必须要,或新�?�?个线�?
    StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
    
    boolean a=dbUtil.deleteUser(cNoEditText.getText().toString());
    if (a)
    {
     dialog.dismiss();
     hideButton(false);
     Toast.makeText(UserListActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
    }
    else
     Toast.makeText(UserListActivity.this, "删除失败", Toast.LENGTH_SHORT).show(); 
   }
  });

  btnCancel.setOnClickListener(new OnClickListener() {

 
   public void onClick(View v) {
    dialog.dismiss();
    hideButton(false);
   }
  });
  
  dialog.show();
 }

 /**
  * 添加帐号信息
  */
 private void setAddDialog() {

  final Dialog dialog = new Dialog(UserListActivity.this);
  dialog.setContentView(R.layout.dialog_add);
  dialog.setTitle("添加数据");
  Window dialogWindow = dialog.getWindow();
  WindowManager.LayoutParams lp = dialogWindow.getAttributes();
  dialogWindow.setGravity(Gravity.CENTER);
  dialogWindow.setAttributes(lp);

  final EditText cNameEditText = (EditText) dialog.findViewById(R.id.editText1);
  final EditText cNumEditText = (EditText) dialog.findViewById(R.id.editText2);
  Button btnConfirm = (Button) dialog.findViewById(R.id.button1);
  Button btnCancel = (Button) dialog.findViewById(R.id.button2);

  btnConfirm.setOnClickListener(new OnClickListener() {


   public void onClick(View v) {
    
    //StrictMode必须要,或新�?�?个线�?
    StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
    
    boolean a=dbUtil.insertCargoInfo(cNameEditText.getText().toString(), cNumEditText.getText().toString());

    if (a)
    {
     dialog.dismiss();
     hideButton(false);
     Toast.makeText(UserListActivity.this, "添加成功", Toast.LENGTH_SHORT).show();
    }
    else
     Toast.makeText(UserListActivity.this, "不添加成�?", Toast.LENGTH_SHORT).show();
     
 /*
    new Thread() 
        { 
            public void run() 
           { 
                try 
                { 
                   //Soap.GetWebServer("insertCargoInfo", arrayList1, arrayList2); 
                 System.out.print("添加�?  添加�?  添加�?  添加前FFF");
        dbUtil.insertCargoInfo(cNameEditText.getText().toString(), cNumEditText.getText().toString());
        //dbUtil.insertCargoInfo("AAA", "111");
      
     
                } 
                catch(Exception e) 
                { 
              Toast.makeText(AddWuLiaoActivity.this, "添加不成成功", Toast.LENGTH_SHORT).show();     
                } 
           } 
        }.start();

    */
    
     
     
     
    
   
    //dbUtil.insertCargoInfo(cNameEditText.getText().toString(), cNumEditText.getText().toString());
    
    
   }
  });

  btnCancel.setOnClickListener(new OnClickListener() {


   public void onClick(View v) {
    dialog.dismiss();
    hideButton(false);
   }
  });
  dialog.show();
 }

 /**
  * 显示帐号信息ListView
  */
 private void setListView() {

  //StrictMode必须要,或新�?�?个线�?
  StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
    
    
  listView.setVisibility(View.VISIBLE);

  List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
  
  
  list = dbUtil.SelectAccountInfo();

 
  adapter = new SimpleAdapter(
    UserListActivity.this,
    list,
    R.layout.adapter_item,
    new String[] { "UserName", "UserCode", "PWD" },
    new int[] { R.id.txt_Cno, R.id.txt_Cname, R.id.txt_Cnum });

  listView.setAdapter(adapter);

  
 }

 /**
  * 鐠佸墽鐤哹utton閻ㄥ嫬褰茬憴浣癸拷锟�?
  */
 private void hideButton(boolean result) {
  if (result) {
   btn1.setVisibility(View.GONE);
   btn2.setVisibility(View.GONE);
   btn3.setVisibility(View.GONE);
  } else {
   btn1.setVisibility(View.VISIBLE);
   btn2.setVisibility(View.VISIBLE);
   btn3.setVisibility(View.VISIBLE);
  }

 }

 /**
  * 鏉╂柨娲栭幐澶愭尦閻ㄥ嫰鍣搁崘锟�?
  */
 @Override
 public void onBackPressed()
 {
  if (listView.getVisibility() == View.VISIBLE) {
   listView.setVisibility(View.GONE);
   hideButton(false);
  }else {
   UserListActivity.this.finish();
  }
 }
}





二: DBUtil类

package User.User.namespace;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.widget.Toast;


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();

 public static Connection getConnection() {
  Connection con = null;
  try {
   //Class.forName("org.gjt.mm.mysql.Driver");
   //con=DriverManager.getConnection("jdbc:mysql://192.168.0.106:3306/test?useUnicode=true&characterEncoding=UTF-8","root","initial");       
  } catch (Exception e) {
   //e.printStackTrace();
  }
  return con;
 }

 /**
  * 获取所有货物的信息
  *
  * @return
  */
 public List<HashMap<String, String>> SelectAccountInfo() {
  List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();

  arrayList.clear();
  brrayList.clear();
  crrayList.clear();

  crrayList = Soap.GetWebServre("selectAccountInfo", arrayList, brrayList);

 
  HashMap<String, String> tempHash = new HashMap<String, String>();
  tempHash.put("PWD","PWD");
  tempHash.put("UserName", "UserName");
  tempHash.put("UserCode", "UserCode");
  list.add(tempHash);
  
  System.out.println(crrayList.size()+" 数据集List 的Size ");  
  
  for (int j = 0; j < crrayList.size(); j += 3) {
   HashMap<String, String> hashMap = new HashMap<String, String>();
   hashMap.put("PWD", crrayList.get(j+1));
   hashMap.put("UserName", crrayList.get(j));
   hashMap.put("UserCode", crrayList.get(j + 2));
   list.add(hashMap);
  }
 
  
  return list;
 }

 /**
  * 增加一条货物信息
  *
  * @return
  */
 public boolean insertCargoInfo(String Cname, String Cnum) {

  
  arrayList.clear();
  brrayList.clear();
  
  //arrayList.add("Cname");
  //arrayList.add("Cnum");
  
  arrayList.add("userName");
  arrayList.add("PWD");
  
  
  brrayList.add(Cname);
  brrayList.add(Cnum);

  String a=Soap.GetWebServre("InsertAccount", arrayList, brrayList).toString();
  
  
  if (a.equals("[false]")||a.equals("false"))    
  {
   System.out.println(a+"sssssssssssssssssssssssssss");
   System.out.print("----"+a+"------添加前 不成功 FALSE  ");
   System.out.print(a);
   return false;
  }
  else
  {
   System.out.print(a);
   System.out.print("----"+a+"----添加前 Ddddddddddddd True  ");
   return true;

  }
   
  /*
  new Thread()
  {
   public void run()
   {
    try
    {
     //Soap.GetWebServer("insertCargoInfo", arrayList1, arrayList2);
     Soap.GetWebServre("InsertAccount", arrayList, brrayList);
 
    }
    catch(Exception e)
    {
     //return;
    }
   }
  }.start();
  */


 }
 
 
 /**
  * 删除一条货物信息
  *
  * @return
  */
 public boolean deleteUser(String userName) {

  arrayList.clear();
  brrayList.clear();
  
  arrayList.add("userName");
  brrayList.add(userName);
  
  String a=Soap.GetWebServre("deleteUser", arrayList, brrayList).toString(); 
  
  if (a.equals("[false]")||a.equals("false"))    
  {
   System.out.print("----"+a+"------删除前 不成功 FALSE  ");
   return false;
  }
  else
   return true;
 }
}



三:HttpSoapConn类


package User.User.namespace;

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
  //4124是指端口号,即挂载到IIS上的时候开启的端口
  //Service1.asmx是指提供服务的页面
  //String ServerUrl = "http://10.0.2.2:11125/Service1.asmx";
  String ServerUrl = "http://192.168.0.17/WebSite1/WebService.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(6000);// 设置超时时间
   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());
   System.out.println(Values.toString()+"Value tostring HttpConnSoap 调试用");
   return Values;

  } catch (Exception e) {
   System.out.print("调试异常  HttpConnSoap的异常"+e.toString());
   return null;
  }
 }

 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 = s1.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.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;
 }

}