如何从PHP服务器获取JSON数据到安卓手机

7

我有一个应用程序,想从php web服务器获取json数据传输到安卓手机上。我有一个URL,访问此URL会给我一个json数据,如下所示:
{"items":[{"latitude":"420","longitude":"421"}]}。 但是我想在我的安卓手机上检索这个json格式,并从中获取纬度和经度的值。

我们如何在安卓手机上实现呢?

提前感谢。


2
使用HTTPClient在Android上与服务器交换数据。如果遇到困难,请发布你的代码,我们会尝试帮助你。 - Aleks G
4个回答

9

首先进行URL连接

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字符串

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

以下是我获取国家详情的代码:
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 "";
    }
}

这个“convertinputStreamToString(is)”方法是什么? - Jagdeep Singh

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

这个 JSON 字符串实际上是来自 http://json.org/example.html。在给定的示例中,这是我能找到的最好的。

现在我们已经有了它,让我们开始使用 JSONObject。为了使其工作,您需要进行以下导入: import org.json.JSONObject;

JSONObject jsonObj = new JSONObject(jsonStr); 

有了这个实例,我们可以从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()); 
}

点击这里查看一个简单的示例。


我该如何在我的程序中获取这个JSON字符串? - Jagdeep Singh
你可以将PHP中的返回字符串转换为JSON格式。 - Ram kiran Pachigolla
我的 PHP URL 返回 JSON 格式,但问题是我该如何在程序中获取它? - Jagdeep Singh
你在哪里传递URL? - Jagdeep Singh

1

从您的Android客户端发送请求

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;

}

这是将字符串转换的函数。
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();
}

现在你所需要做的就是在服务器上以JSON格式echo你的字符串。

0

使用类似以下的代码:

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();
}

如果你告诉我可能出现的异常,我可以帮忙解决。这段代码在我的电脑上是可以运行的,除了 JSON 部分不同之外。 - Nermeen
我不知道是什么异常,但当我在 catch 块中 toast 某些内容时,它会被 toast,但当我 toast 纬度和经度时,它就不会被 toast。 - Jagdeep Singh
urlstring需要用""传递吗? - Jagdeep Singh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接