Android调用webservice接收json

Android端

<pre name="code" class="java">package com.example.wsapp;



import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.example.model.User;

public class MainActivity extends Activity {

	private Button button;

	// WS
	private static String NAME_SPACE = "http://train.shd.com/";
	private static String METHOD_NAME = "getAllUsers";
	private static String WSDL_URL = "http://10.211.96.131:8080/ServiceTrain/TestPort?wsdl";
//	private String SOAP_ACTION = "http://hello.shd.com/sayHello";  
	
	private UserTask userTask;
	
	private ListView listView;
	private ListAdapter adapter;
	private ProgressDialog dialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		button = (Button) findViewById(R.id.button1);
		button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				userTask = new UserTask();
				userTask.execute();
			}
		});
		
		listView = (ListView)findViewById(R.id.listView);
		dialog = new ProgressDialog(this);
		dialog.setMessage("正在加载,请稍后。。。");
//		.setMessage("")
	}

	class UserTask extends AsyncTask<Void, Void, List<User>> {
		
		@Override
		protected void onPreExecute() {
			dialog.show();
			super.onPreExecute();
		}

		@Override
		protected List<User> doInBackground(Void... params) {
			List<User> data = new ArrayList<User>();
			User user;
			
			SoapObject request = new SoapObject(NAME_SPACE, METHOD_NAME);
			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
			envelope.bodyOut = request;
			
			envelope.setOutputSoapObject(request); 
			
			HttpTransportSE ht = new HttpTransportSE(WSDL_URL);
			ht.debug = true;

			try {
				ht.call(null, envelope);
				if(envelope.getResponse() != null){
					//在服务器端返回值是String类型的数值的时候使用SoapObject soapObject = (SoapObject) envelope.getResponse();
					//和 SoapObject result = (SoapObject)envelope.bodyIn;这两种方法来接受值都会报出
					//java.lang.ClassCastException: org.ksoap2.serialization.SoapPrimitive这样的错误。 我们可以使用 Object object = 
					//envelope.getResponse();就可以解决这种错误。或者 
					//org.ksoap2.serialization.SoapPrimitive soapPrimitive =(SoapPrimitive) envelope.getResponse(); 
					
					//服务器返回String类型的json,直接传回json获取不到数据。
					SoapPrimitive result = (SoapPrimitive) envelope.getResponse();
					JSONObject obj = new JSONObject(result.toString());
					JSONArray jsonArray = (JSONArray)obj.getJSONArray("data");
					
					for (int i = 0; i < jsonArray.length(); i++) {
						JSONObject json = jsonArray.getJSONObject(i);
						user = new User();
						user.setName(json.getString("name"));
						user.setPassword(json.getString("phone"));
						data.add(user);
					}
					
				}
				
			} catch (IOException e) {
				e.printStackTrace();
			} catch (XmlPullParserException e) {
				e.printStackTrace();
			}  catch (org.json.JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return data;
		}

		@Override
		protected void onPostExecute(List<User> result) {
			dialog.dismiss();
			if (adapter == null) {
				adapter = new ListAdapter(result);
				listView.setAdapter(adapter);
			}else{
				adapter.listData = result;
				adapter.notifyDataSetChanged();
			}
			super.onPostExecute(result);
		}
	}
	
	class ListAdapter extends BaseAdapter{

		private List<User> listData;
		
		public ListAdapter(List<User> listData) {
			super();
			this.listData = listData;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return listData.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return listData.size();
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder viewHolder = null;
			if(convertView == null){
				viewHolder = new ViewHolder();
				convertView = LayoutInflater.from(MainActivity.this).inflate(R.layout.list_item, null);
				viewHolder.tv_name = (TextView)convertView.findViewById(R.id.tv_namevalue);
				viewHolder.tv_password = (TextView)convertView.findViewById(R.id.tv_phonevalue);
				convertView.setTag(viewHolder);
			}else{
				viewHolder = (ViewHolder)convertView.getTag();
			}
			User user = listData.get(position);
			viewHolder.tv_name.setText(user.getName());
			viewHolder.tv_password.setText(user.getPassword());
			
			return convertView;
		}
		
		class ViewHolder{
			TextView tv_name;
			TextView tv_password;
		}
		
	}

}

 

服务器端:

package com.shd.train;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;


public class Test {

	public String getNumString() {
		return "shd";
	}

	/**
	 * 获取用户信息
	 * @return
	 */
	public List<UserInfo> getUser() {
		List<UserInfo> list = new ArrayList<UserInfo>();
		UserInfo userInfo = new UserInfo();

		userInfo.setId(1);
		userInfo.setUserName("张三");
		userInfo.setPassword("123");
		userInfo.setSex("男");
		userInfo.setAge(19);
		list.add(userInfo);

		userInfo = new UserInfo();
		userInfo.setId(2);
		userInfo.setUserName("李四");
		userInfo.setPassword("456");
		userInfo.setSex("女");
		userInfo.setAge(18);
		list.add(userInfo);

		return list;
	}
	
	/**
	 * 根据ID获取用户信息
	 * @return
	 */
	public UserInfo getUserById(int id) {
		UserInfo userInfo = new UserInfo();

		userInfo.setId(id);
		userInfo.setUserName("虚拟用户:张三");
		userInfo.setPassword("123");
		userInfo.setSex("男");
		userInfo.setAge(19);


		return userInfo;
	}
	
	
	public static String getAllUsers() {
		String url = "jdbc:mysql://localhost:3306/train";
		String username = "root";
		String password = "111111";
		Statement stmt = null;
		ResultSet rs = null;
		Connection conn = null;
		JSONObject returnJson = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection(url, username, password);
			stmt = conn.createStatement();
			String sql = "Select name,phone from fnd_user";
			// CallableStatement prepareCall = conn.prepareCall(sql);
			rs = stmt.executeQuery(sql);
			JSONObject json = null;
			JSONArray jsonArray = new JSONArray();
			returnJson = new JSONObject();
			while (rs.next()) {
				json = new JSONObject();
				json.put("name", rs.getString(1));
				json.put("phone", rs.getString(2));
				jsonArray.add(json);
			}
			returnJson.put("time",System.currentTimeMillis());
			returnJson.put("data", jsonArray);
		} catch (Exception e) {
			try {
				if (rs != null) { // 关闭记录集
					rs.close();
				}
				if (stmt != null) { // 关闭声明
					stmt.close();
				}
				if (conn != null) { // 关闭连接对象
					conn.close();
				}
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}

		}
		return returnJson.toString();

	}
	
	
	public static List<UserInfo> getListUsers() {
		String url = "jdbc:mysql://localhost:3306/train";
		String username = "root";
		String password = "111111";
		Statement stmt = null;
		ResultSet rs = null;
		Connection conn = null;
		JSONObject returnJson = null;
		List<UserInfo> users = new ArrayList<UserInfo>();
		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection(url, username, password);
			stmt = conn.createStatement();
			String sql = "Select name,phone from fnd_user";
			// CallableStatement prepareCall = conn.prepareCall(sql);
			rs = stmt.executeQuery(sql);
			UserInfo user = null;
			
			returnJson = new JSONObject();
			while (rs.next()) {
				user = new UserInfo();
				user.setUserName(rs.getString(1));
				users.add(user);
				if (users.size() ==10) {
					break;
				}
			}
		} catch (Exception e) {
			try {
				if (rs != null) { // 关闭记录集
					rs.close();
				}
				if (stmt != null) { // 关闭声明
					stmt.close();
				}
				if (conn != null) { // 关闭连接对象
					conn.close();
				}
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}

		}
		return users;

	}

}

点击下载代码


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值