Android客户端与服务器之间传递json数据
生活随笔
收集整理的這篇文章主要介紹了
Android客户端与服务器之间传递json数据
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在服務器與客戶端之間通信,json數據是一種常用格式,本文主要在服務器端構建數據,在客戶端接收顯示,并且在listview上顯示出來
服務器端的構建
簡單的javabean與返回結果函數與插入函數略過
public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("text/html");response.setCharacterEncoding("UTF-8");PrintWriter out = response.getWriter();List<MyShop> shops = JsonService.getListShop();StringBuffer sb = new StringBuffer();sb.append('[');for (MyShop shop : shops) {sb.append('{').append("\"name\":").append("\""+shop.getName()+"\"").append(","); sb.append("\"detail\":").append("\""+shop.getDetail()+"\"").append(",");sb.append("\"distance\":").append("\""+shop.getDistance()+"\"").append(",");sb.append("\"address\":").append("\""+shop.getAddress()+"\"").append(",");sb.append("\"popularity\":").append(shop.getPopularity());sb.append('}').append(",");}sb.deleteCharAt(sb.length() - 1);sb.append(']');out.write(new String(sb));out.flush();out.close();}在瀏覽器中直接輸入訪問http://localhost:8080/AppServer/JsonServlet
可得
可以在服務器端直接查看json數據
客戶端接收與解析json數據
public class JsonParse {/*** 解析Json數據** @param urlPath* @return mlists* @throws Exception*/public static List<MyShop> getListShop(String urlPath) throws Exception {List<MyShop> mlists = new ArrayList<MyShop>();byte[] data = readParse(urlPath);JSONArray array = new JSONArray(new String(data));for (int i = 0; i < array.length(); i++) {JSONObject item = array.getJSONObject(i);String name = item.getString("name");String detail = item.getString("detail");String distance = item.getString("distance");String popularity = item.getString("popularity");String address = item.getString("address");mlists.add(new MyShop(name, detail, distance,address,popularity));}return mlists;}/*** 從指定的url中獲取字節數組** @param urlPath* @return 字節數組* @throws Exception*/public static byte[] readParse(String urlPath) throws Exception {ByteArrayOutputStream outStream = new ByteArrayOutputStream();byte[] data = new byte[1024];int len = 0;URL url = new URL(urlPath);HttpURLConnection conn = (HttpURLConnection) url.openConnection();InputStream inStream = conn.getInputStream();while ((len = inStream.read(data)) != -1) {outStream.write(data, 0, len);}inStream.close();return outStream.toByteArray();}}在activity中開啟子線程來接收服務器數據
new Thread(new Runnable() {private String tag;@Overridepublic void run() {// TODO Auto-generated method stub//獲得新聞集合List<MyShop> shopList = null;try {shopList = JsonParse.getListShop("http://192.168.247.1:8080/AppServer/JsonServlet");} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}Log.i(tag, "在RUN中LIST長度為"+shopList.size());Message msg=new Message();if(shopList!=null){msg.what=SUCCESS;msg.obj=shopList;}else{msg.what=FAILED;}handler.sendMessage(msg);Log.i(tag, "***********T長度為"+shopList.size());}}).start();消息處理器
//消息處理器private Handler handler=new Handler(){/*** 接收消息*/@Overridepublic void handleMessage(Message msg) {// TODO Auto-generated method stubString tag = null;switch (msg.what) {case SUCCESS: //訪問成功,有數據//綁定數據Log.i(tag,"%%%%%%%%%%到達了消息處理器");myshoplist=(List<MyShop>) msg.obj;Log.i(tag, "handleMessage中數據newInfoList長度為"+myshoplist.size());NearAdapter adapter=new NearAdapter();Log.i(tag, "有沒有到達ADAPTER"+adapter.getCount());showList.setAdapter(adapter);break;case FAILED: //訪問失敗Toast.makeText(ChooseMer.this, "當前網絡崩潰了", 0).show();break;default:break;}}};配置適配器
public class NearAdapter extends BaseAdapter {@Overridepublic int getCount() {// TODO Auto-generated method stubreturn myshoplist.size();}@Overridepublic Object getItem(int position) {// TODO Auto-generated method stubreturn null;}@Overridepublic long getItemId(int position) {// TODO Auto-generated method stubreturn 0;}@Overridepublic View getView(int position, View convertView, ViewGroup parent) {if (convertView == null) {LayoutInflater inflater = LayoutInflater.from(ChooseMer.this);convertView = inflater.inflate(R.layout.nearby_list_item, null);init(convertView,position);}return convertView;}public void init(View convertView,int position) {hold.name = (TextView) convertView.findViewById(R.id.nearby_item_name);MyShop shop=myshoplist.get(position);hold.name.setText(shop.getName());hold.local = (TextView) convertView.findViewById(R.id.nearby_item_local);hold.local.setText(shop.getDetail());hold.dis1 = (TextView) convertView.findViewById(R.id.nearby_item_dis1);hold.dis1.setText(shop.getDistance());hold.dis2 = (TextView) convertView.findViewById(R.id.nearby_item_dis2);hold.dis2.setText(shop.getAddress());hold.dis3 = (TextView) convertView.findViewById(R.id.nearby_item_dis3);hold.dis3.setText(shop.getPopularity());}}配置完成,效果如下
總結
以上是生活随笔為你收集整理的Android客户端与服务器之间传递json数据的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: struts2服务端与android交互
- 下一篇: Android之Bundle类