android - 如何从服务器下载 JSON 的示例?

标签 android xml json httpclient

是否有很好的示例说明如何查询服务器并下载响应(JSON 或 XML)?

最佳答案

这应该可以解决问题

String JsonResponse = HttpHelper.connect(SERVER_URL);
JSONObject json=new JSONObject(JsonResponse);

private static String convertStreamToString(InputStream is) {
        /*
         * To convert the InputStream to String we use the BufferedReader.readLine()
         * method. We iterate until the BufferedReader return null which means
         * there's no more data to read. Each line will appended to a StringBuilder
         * and returned as String.
         */
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        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();
    }
    public static String connect(String url)
    {
        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(url); 
        HttpResponse response;
        try {
            response = httpclient.execute(httpget);
            //Log.i(TAG,response.getStatusLine().toString());
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream instream = entity.getContent();
                String result= convertStreamToString(instream);
                instream.close();
                return result;
            }
        } catch (ClientProtocolException e) {
        } catch (IOException e) {
        }
        return null;
    }

关于android - 如何从服务器下载 JSON 的示例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3578441/

相关文章:

android - ffmpeg如何将解码的音频数据保存到pcm

android - TextInputLayout 抛出 "The style on this component requires your app theme to be Theme.AppCompat (or a descendant)."

json - 如何在嵌套对象 SWIFT 中获取值

json - 阅读 Pyspark Struct Json Column 非必需元素

ruby-on-rails - 无法将签名板的JSON转换为回形针图像(Ruby on Rails)

android - 在 Android Studio 2.2 之后默认按下带有 9 补丁边框的 MenuItem

java - 使用Recyclerview解析Json

android - LayoutInflater 用于使用 xml 和 View 类

如果 XML 属性不存在则忽略该属性的 Pythonic 方法

XML 节点的 python 报告行/原始列