从android中的URL检索Json对象或String

时间:2015-10-08 05:10:13

标签: android json httpclient httpurlconnection

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

3 个答案:

答案 0 :(得分:0)

我建议使用square http://square.github.io/retrofit/

提供的Retrofit库

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

答案 1 :(得分:0)

下面我提供了如何使用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);

谢谢.. !!

答案 2 :(得分:0)

您可以使用此方法获取完整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对象。

快乐编码