【问题标题】:Retrieving Json object or String from a URL in android从 android 中的 URL 检索 Json 对象或字符串
【发布时间】:2015-10-08 05:10:12
【问题描述】:

有很多关于如何做到这一点的教程,但都有一个问题,它们都使用 httpclient 或其他一些在最新 sdk 中已弃用的函数或类。请任何人发布如何获取 Json 对象或来自使用最新 HttpUrlConnection 的 URL 的字符串。我试过了,但没有用。请发布完整的教程。 示例网址:http://api.openweathermap.org/data/2.5/weather?q=ranchi

【问题讨论】:

  • 你可以使用volley..!!
  • 可以发一下教程吗?我试图从 android 开发者网站上读取它,但无法让它运行..
  • @ Gaurav Chaddha:是的,当然..!!
  • @GauravChaddha,其他选项是改造库themakeinfo.com/2015/04/retrofit-android-tutorial
  • 你可以在this的帮助下做到这一点

标签: android json httpclient httpurlconnection


【解决方案1】:

我会推荐使用 square http://square.github.io/retrofit/ 提供的 Retrofit 库

这是一个实现改造的教程 https://guides.codepath.com/android/Consuming-APIs-with-Retrofit

【讨论】:

    【解决方案2】:

    下面我提供了如何使用 volley 请求打开天气服务器:

    将以下依赖项添加到您的 gradle 中:

    compile 'com.mcxiaoke.volley:library:1.0.19'
    

    获取当前天气数据的方法:

    /**
         * To get current weather
         *
         * @param latitude        : a current latitude
         * @param longitude       : a current longitude
         */
        public void getCurrentWeatherData(double latitude, double longitude) {
    
        final String URL_CURRENT_WEATHER = "http://api.openweathermap.org/data/2.5/weather?";
        final String WEATHER_API_KEY = "8bf8ba5fa2f008b8bdda9cded4edf109";
        Uri builtUri = Uri.parse(URL_CURRENT_WEATHER).buildUpon()
                .appendQueryParameter("lat", String.valueOf(latitude))
                .appendQueryParameter("lon", String.valueOf(longitude))
                .appendQueryParameter("units", "metric")
                .appendQueryParameter("APPID", WEATHER_API_KEY).build();
    
        JsonObjectRequest registrationRequest = new JsonObjectRequest(Request.Method.GET, builtUri.toString(),
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Log.d(TAG, response.toString());
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d(TAG, error.getMessage());
            }
        });
        Log.e(TAG, registrationRequest.getUrl());
        RequestQueue queue = Volley.newRequestQueue(this);
       queue.add(registrationRequest);
    }
    

    如何调用这个方法:

      getCurrentWeatherData(27,72);
    

    谢谢..!!

    【讨论】:

      【解决方案3】:

      可以使用该方法获取完整的Json字符串

        public static String httpGet() throws IOException {
        URL url = http://api.openweathermap.org/data/2.5/weather?q=ranchi
        HttpURLConnection conn =
        (HttpURLConnection) url.openConnection();
      
        if (conn.getResponseCode() != 200) {
        throw new IOException(conn.getResponseMessage());
       }
      
      // Buffer the result into a string
        BufferedReader rd = new BufferedReader(
        new InputStreamReader(conn.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = rd.readLine()) != null) {
        sb.append(line);
       }
       rd.close();
      
       conn.disconnect();
       return sb.toString();
       }
      

      现在您可以从字符串中创建一个 json 对象,例如

      JSONObject jsonResponse =  new JSONObject(httpGet());
      

      使用 jsonResponse,无论 jsonResponse 中是否存在数组、字符串或其他 json 对象,您都可以相应地工作。

      愉快的编码

      【讨论】:

      • 如需进一步查询,请随时询问。我会尽力帮助你
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-28
      • 2012-10-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多