Android获取json数据的原理,我的理解是:首先通过http协议获取json数据的字符串格式数据,然后再把字符串格式转变成Json对象的数据

首先我先将某个网址path的数据获取到:

 1 /**
 2  * HttpUtils.java [V 1.0.0]
 3  * classes :com.oysd.json.HttpUtils
 4  * ouyangshengduo create at 2015-6-24
 5  */
 6 package com.oysd.json;
 7 
 8 import java.io.ByteArrayOutputStream;
 9 import java.io.IOException;
10 import java.io.InputStream;
11 import java.net.HttpURLConnection;
12 import java.net.MalformedURLException;
13 import java.net.URL;
14 
15 /**
16  * com.oysd.json.HttpUtils
17  * @author ouyangshengduo
18  * create at 2015-6-24
19  */
20 public class HttpUtils {
21 
22     public HttpUtils() { 
23     } 
24      
25     public static String getJsonContent(String path){ 
26         try { 
27             URL url = new URL(path); 
28             HttpURLConnection connection = (HttpURLConnection)url.openConnection(); 
29             connection.setConnectTimeout(3000); 
30             connection.setRequestMethod("GET"); 
31             connection.setDoInput(true); 
32             int code = connection.getResponseCode(); 
33             if(code == 200){ 
34                 //获取数据输入流
35                 return changeInputStream(connection.getInputStream()); 
36             } 
37         } catch (MalformedURLException e) { 
38             e.printStackTrace(); 
39         } catch (IOException e) { 
40             e.printStackTrace(); 
41         } 
42         return null; 
43     } 
44  
45     /** 
46      * 将一个输入流转换成指定编码的字符串
47      * @param inputStream 
48      * @return 
49      */ 
50     private static String changeInputStream(InputStream inputStream) { 
51         String jsonString = ""; 
52         ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); 
53         int len = 0; 
54         //把输入流转换成字符串
55         byte[] data = new byte[1024]; 
56         try { 
57             while((len=inputStream.read(data))!=-1){ 
58                 outputStream.write(data,0,len); 
59             } 
60             jsonString = new String(outputStream.toByteArray()); 
61         } catch (IOException e) { 
62             e.printStackTrace(); 
63         } 
64         return jsonString; 
65     } 
66 }
View Code

相关文章: