繁体   English   中英

Android从URL响应中获取JSON响应,从本地主机获取错误和错误

[英]Android get json from url response null and error from localhost

我有一个android java源代码:

private void getDataFromServer(String url){
        InputStream is = null;
        JSONObject json = null;
        String output = "";
        URL _url;
        URLConnection urlConnection = null;

        try {
            _url = new URL(url);
            urlConnection = _url.openConnection();
        }
        catch (MalformedURLException e) {
            Log.e("JSON Parser", "Error due to a malformed URL " + e.toString());

        }
        catch (IOException e) {
            Log.e("JSON Parser", "IO error " + e.toString());

        }

        try {
            urlConnection.setRequestProperty("Accept-Charset", "UTF-8");
            urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
            is = new BufferedInputStream(urlConnection.getInputStream());
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            StringBuilder total = new StringBuilder(is.available());
            String line;
            while ((line = reader.readLine()) != null) {
                total.append(line).append('\n');
            }
            output = total.toString();
        }
        catch (IOException e) {
            Log.e("JSON Parser", "IO error " + e.toString());

        }
//        finally{
//            urlConnection.disconnect();
//        }

        try {
            json = new JSONObject(output);
        }
        catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }
    }

URL = http://localhost/API/getdata.php将返回:

[
    {
        "id": "1",
        "nama_kab": "KAB. BOGOR",
        "jml_miskin": "479",
        "presentase_miskin": "8.91",
        "indeks_kedalaman": "1.27",
        "indeks_keparahan": "0.29",
        "garis_kemiskinan": "280312",
        "latitude": "-6.59504",
        "longitude": "106.817"
    }
]

我使用调试和断点,当: is = new BufferedInputStream(urlConnection.getInputStream());时,它总是停止并出错is = new BufferedInputStream(urlConnection.getInputStream()); 我尝试添加字符集和任何其他stackoverflow建议,但仍然错误。 请帮我

这是我的清单:

<uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

首先,响应不是一个对象( JSONObject ),而是一个数组,因此您应该相应地进行解析(使用JSONArray )。 其次, Content-Type是服务器发送的标头,客户端使用Accept标头指示期望的数据类型。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM