2012-07-20 36 views
7

Tôi đang có một ứng dụng mà tôi muốn lấy dữ liệu json từ máy chủ web php đến điện thoại di động Android. những gì tôi đang có là một url và nhấn url đó cung cấp cho tôi dữ liệu json như
{"items":[{"latitude":"420","longitude":"421"}]}. Nhưng tôi muốn lấy định dạng json này trong điện thoại di động Android của tôi và nhận được các giá trị vĩ độ và kinh độ từ định dạng json.cách lấy dữ liệu json từ máy chủ php tới điện thoại di động Android

làm thế nào chúng ta có thể nhận được điều đó trên điện thoại di động Android ..?

Thanks in advance ..

+2

Sử dụng HttpClient trên Android để trao đổi dữ liệu với máy chủ. Nếu bạn gặp khó khăn, hãy đăng mã của bạn và chúng tôi sẽ cố gắng trợ giúp. –

Trả lời

9

Đầu tiên làm URL kết nối

String parsedString = ""; 

    try { 

     URL url = new URL(yourURL); 
     URLConnection conn = url.openConnection(); 

     HttpURLConnection httpConn = (HttpURLConnection) conn; 
     httpConn.setAllowUserInteraction(false); 
     httpConn.setInstanceFollowRedirects(true); 
     httpConn.setRequestMethod("GET"); 
     httpConn.connect(); 

     InputStream is = httpConn.getInputStream(); 
     parsedString = convertinputStreamToString(is); 

    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

JSON Chuỗi

{ 
"result": "success", 
"countryCodeList": 
[ 
    {"countryCode":"00","countryName":"World Wide"}, 
    {"countryCode":"kr","countryName":"Korea"} 
] 
} 

Đây dưới đây tôi lấy chi tiết nước

JSONObject json = new JSONObject(jsonstring); 
JSONArray nameArray = json.names(); 
JSONArray valArray = json.toJSONArray(nameArray); 

JSONArray valArray1 = valArray.getJSONArray(1); 

valArray1.toString().replace("[", ""); 
valArray1.toString().replace("]", ""); 

int len = valArray1.length(); 

for (int i = 0; i < valArray1.length(); i++) { 

Country country = new Country(); 
JSONObject arr = valArray1.getJSONObject(i); 
country.setCountryCode(arr.getString("countryCode"));       
country.setCountryName(arr.getString("countryName")); 
arrCountries.add(country); 
} 




public static String convertinputStreamToString(InputStream ists) 
     throws IOException { 
    if (ists != null) { 
     StringBuilder sb = new StringBuilder(); 
     String line; 

     try { 
      BufferedReader r1 = new BufferedReader(new InputStreamReader(
        ists, "UTF-8")); 
      while ((line = r1.readLine()) != null) { 
       sb.append(line).append("\n"); 
      } 
     } finally { 
      ists.close(); 
     } 
     return sb.toString(); 
    } else { 
     return ""; 
    } 
} 
+0

phương thức 'convertinputStreamToString (is)' này là gì? –

+0

Tôi đã thêm phương thức – Nirali

0

Sử dụng một cái gì đó như :

try { 
    HttpParams params = new BasicHttpParams(); 
    HttpConnectionParams.setSoTimeout(params, 0); 
    HttpClient httpClient = new DefaultHttpClient(params); 

    //prepare the HTTP GET call 
    HttpGet httpget = new HttpGet(urlString); 
    //get the response entity 
    HttpEntity entity = httpClient.execute(httpget).getEntity(); 

    if (entity != null) { 
     //get the response content as a string 
     String response = EntityUtils.toString(entity); 
     //consume the entity 
     entity.consumeContent(); 

     // When HttpClient instance is no longer needed, shut down the connection manager to ensure immediate deallocation of all system resources 
     httpClient.getConnectionManager().shutdown(); 

     //return the JSON response 
     JSONObject object = new JSONObject(response.trim()); 
     JSONArray jsonArray = object.getJSONArray("items"); 
     if(jsonArray != null) { 
      for(int i = 0 ; i < jsonArray.length() ; i++) { 
       JSONObject object1 = (JSONObject) jsonArray.get(i); 
       String latitude = object1.getString("latitude"); 
       String longitude = object1.getString("longitude"); 
      } 
     } 
    } 
}catch (Exception e) { 
    e.printStackTrace(); 
} 
+0

mã của bạn sẽ tham gia vào khối catch ... tại sao lại như vậy ?? –

+0

nếu bạn cho tôi biết ngoại lệ có thể là gì tôi có thể trợ giúp, mã này đang hoạt động đối với tôi, ngoại trừ phần JSON khác. – Nermeen

+0

Tôi không biết ngoại lệ là gì nhưng khi tôi nướng bánh mì trong khối catch nó có được nướng nhưng khi tôi nướng bánh mì vĩ độ và kinh độ nó không bánh mì nướng. –

1
String jsonStr = '{"menu": {' + 
     '"id": "file",' + 
     '"value": "File",' + 
     '"popup": {' + 
      '"menuitem": [' + 
      '{"value": "New", "onclick": "CreateNewDoc()"},' + 
      '{"value": "Open", "onclick": "OpenDoc()"},' + 
      '{"value": "Close", "onclick": "CloseDoc()"}' + 
      ']' + 
     '}' + 
     '}}'; 

Đó JSON chuỗi thực sự là từ http://json.org/example.html. Đó là một trong những tốt nhất tôi có thể tìm thấy cho ví dụ này.

Bây giờ chúng ta đã có sẵn, hãy bắt đầu sử dụng JSONObject. Bạn sẽ cần nhập khẩu sau đây để làm việc này: import org.json.JSONObject;

JSONObject jsonObj = new JSONObject(jsonStr); 

Với instantiated, chúng ta có thể làm như sau để truy xuất phần khác nhau của dữ liệu từ chuỗi JSON -

// grabbing the menu object 
JSONObject menu = jsonObj.getJSONObject("menu"); 


Reading =========> HttpResponse response = httpclient.execute(httppost); 
      HttpEntity entity = response.getEntity(); 
      is = entity.getContent(); 
      BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8); 
       StringBuilder sb = new StringBuilder(); 
       String line = null; 
       while ((line = reader.readLine()) != null) 
       { 
        sb.append(line + "\n"); 
       } 
       is.close(); 
       result=sb.toString();=======>Here result is the json string 


// these 2 are strings 
String id = menu.getString("id"); 
String value = menu.getString("value"); 

// the popop is another JSON object 
JSONObject popup = menu.getJSONObject("popup"); 

// using JSONArray to grab the menuitems from under popop 
    JSONArray menuitemArr = popupObject.getJSONArray("menuitem"); 

// lets loop through the JSONArray and get all the items 
for (int i = 0; i < menuitemArr.length(); i++) { 
// printing the values to the logcat 
Log.v(menuitemArr.getJSONObject(i).getString("value").toString()); 
Log.v(menuitemArr.getJSONObject(i).getString("onclick").toString()); 
} 

Đối với một ví dụ đơn giản bấm here

+0

cách tôi sẽ nhận được chuỗi json này trong chương trình của mình ?? –

+0

mà bạn có thể chuyển đổi chuỗi trả về của bạn trong php thành định dạng json –

+0

url php của tôi là trả về định dạng json nhưng điều là làm thế nào tôi sẽ nhận được điều đó trong progarm của tôi? –

1

gửi một yêu cầu từ khách hàng Android của bạn

public static JSONObject getJSONFromHttpPost(String URL) { 

    try{ 
    // Create a new HttpClient and Post Header 
    DefaultHttpClient httpclient = new DefaultHttpClient(); 
    HttpPost httpPost = new HttpPost(URL); 
    String resultString = null; 




     long t = System.currentTimeMillis(); 
     HttpResponse response = (HttpResponse) httpclient.execute(httpPost); 
     System.out.println("HTTPResponse received in [" + (System.currentTimeMillis()-t) + "ms]"); 
     // Get hold of the response entity (-> the data): 
     HttpEntity entity = response.getEntity(); 

     if (entity != null) { 
      // Read the content stream 
      InputStream instream = entity.getContent(); 

      // convert content stream to a String 
      resultString= convertStreamToString(instream); 
      instream.close(); 
      System.out.println("result String : " + resultString); 
      //resultString = resultString.substring(1,resultString.length()-1); // remove wrapping "[" and "]" 
      System.out.println("result String : " + resultString); 
      // Transform the String into a JSONObject 
      JSONObject jsonObjRecv = new JSONObject(resultString); 
      // Raw DEBUG output of our received JSON object: 
      System.out.println("<JSONObject>\n"+jsonObjRecv.toString()+"\n</JSONObject>"); 


      return jsonObjRecv; 
     } 
     }catch(Exception e){e.printStackTrace();} 


     return null; 

}

đây là chức năng để chuyển đổi chuỗi

private static String convertStreamToString(InputStream is) { 

    BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 
    StringBuilder sb = new StringBuilder(); 

    String line =""; 
    try { 
     while ((line = reader.readLine()) != null) { 
      sb.append(line + "\n"); 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } finally { 
     try { 
      is.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
    return sb.toString(); 
} 

bây giờ tất cả bạn phải làm là echo chuỗi của bạn ở định dạng JSON trên máy chủ

Các vấn đề liên quan