安卓客户端与服务器交互Json数据
---恢复内容开始---
1.首先要定义一个Internet类用于连接服务器
1 public class Internet { 2 public static String gethttpresult(String urlStr){ 3 try { 4 URL url=new URL(urlStr); 5 HttpURLConnection connect=(HttpURLConnection)url.openConnection(); 6 InputStream input=connect.getInputStream(); 7 BufferedReader in = new BufferedReader(new InputStreamReader(input)); 8 String line = null; 9 System.out.println(connect.getResponseCode()); 10 StringBuffer sb = new StringBuffer(); 11 while ((line = in.readLine()) != null) { 12 sb.append(line); 13 } 14 return sb.toString(); 15 } catch (Exception e) { 16 System.out.println(e.toString()); 17 return null; 18 } 19 } 20 }
2.定义一个JsonParser类用于解析Json数据
1 public class JSONParser { 2 static InputStream is = null; 3 static JSONArray jObj = null; 4 static String json = ""; 5 // constructor 6 public JSONParser() { 7 } 8 public JSONArray makeHttpRequest(final String url, String method, final List<NameValuePair> params) { 9 // Making HTTP request 10 new Thread(){ 11 @Override 12 public void run() { 13 try { 14 //使用POST请求 15 DefaultHttpClient httpClient = new DefaultHttpClient(); 16 HttpPost httpPost = new HttpPost(url); 17 httpPost.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8)); 18 HttpResponse httpResponse = httpClient.execute(httpPost); 19 HttpEntity httpEntity = httpResponse.getEntity(); 20 is = httpEntity.getContent(); 21 } catch (UnsupportedEncodingException e) { 22 e.printStackTrace(); 23 } catch (ClientProtocolException e) { 24 e.printStackTrace(); 25 } catch (IOException e) { 26 e.printStackTrace(); 27 } 28 try { 29 BufferedReader reader = new BufferedReader(new InputStreamReader( 30 is, "UTF-8")); 31 StringBuilder sb = new StringBuilder(); 32 String line = null; 33 while ((line = reader.readLine()) != null) { 34 sb.append(line + "\n"); 35 } 36 is.close(); 37 json = sb.toString(); 38 } catch (Exception e) { 39 Log.e("Buffer Error", "Error converting result " + e.toString()); 40 Log.d("json", json.toString()); 41 } 42 } 43 }.start(); 44 return jObj; 45 } 46 }
3.在MainActivity中获取并解析获取到的Json数据
1 private Internet internet; 2 //将服务器上的图片加载到本地 3 new Thread() { 4 @Override 5 public void run() { 6 String result = internet.gethttpresult(url); 7 try { 8 JSONObject result_json = new JSONObject(result); 9 JSONArray person = result_json.getJSONArray("data"); 10 for (int i = 0; i < person.length(); i++) { 11 JSONObject object = person.getJSONObject(i); 12 String urL = object.getString("image"); 13 String newPicture=getString(urL); 14 picture.add(newPicture); 15 lastUrl.add(urL); 16 } 17 //这里可以添加你所需要的操作 18 //处理完成后给handler发送消息 19 Message msg = new Message(); 20 msg.what = COMPLETED; 21 handler.sendMessage(msg); 22 } catch (JSONException e) { 23 e.printStackTrace(); 24 System.out.println(e.toString()); 25 Looper.prepare(); 26 Toast.makeText(LoadBmpFeatureActivity.this, "文件解析错误!", Toast.LENGTH_SHORT).show(); 27 Looper.loop(); 28 } 29 } 30 }.start();
获取到的Json格式如下



浙公网安备 33010602011771号