【问题标题】:Passing URL string to AsyncTask将 URL 字符串传递给 AsyncTask
【发布时间】:2014-11-25 17:49:21
【问题描述】:

我正在尝试做一个简单的天气应用程序,它允许用户输入他们的城市并返回天气数据。我正在使用一个具有 EditText 的片段,并且我正在使用一个接口将字符串传递给 MainActivity,这将需要在 URL 字符串中连接,这就是问题所在。得到一个异常错误,我相信协议未找到。我确实检查了我的 URL 是否输入了 http: 或 https。将 URL 传递给我的 AsyncTask 的任何建议

//接口方法

  @Override
    public void displayCityChosen(String cityName) {

    Log.i(TAG, "city name= " +cityName);
    String weatherURL = "http://www.api.openweathermap.org/data/2.5/weather?q=" + cityName + "&APPID=32c831d8a6937f237acff8eef3d4a58c";
    try{

        String base = URLEncoder.encode(weatherURL,"UTF-8");
        URL finalWeatherURL = new URL(base);
       new GetWeather().execute(finalWeatherURL);
    }catch (Exception e) {
        Log.i(TAG, "ERROR");
    }
}

private class GetWeather extends AsyncTask<URL, Void, JSONObject> {

    @Override
    protected JSONObject doInBackground(URL... urls) {

        int statusCode = -1;
        String jsonString = "";

        for (URL queryURL : urls) {
            try {
                URLConnection conn = queryURL.openConnection();
                jsonString = IOUtils.toString(conn.getInputStream());
                jsonResponse = new JSONObject(jsonString);

                jsonArray = jsonResponse.getJSONArray("weather");
                Log.i(TAG, "Array= " + jsonArray);
                break;
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }


        return jsonResponse;
    }


}

【问题讨论】:

标签: android android-asynctask android-json


【解决方案1】:

我认为您需要多一步将 URL 更改为 HttpURLConnection,我认为您使用的这个 url 不需要编码。编码所做的只是弄乱斜线。

        URL url = new URL("http://blah");

        HttpURLConnection httpURLConnection = (HttpURLConnection) url
                .openConnection();
        httpURLConnection.setRequestMethod("GET");
        httpURLConnection.setDoInput(true);

        if (httpURLConnection.getResponseCode() != 200) {
            return null;
        }

        InputStream result = httpURLConnection.getInputStream();
        InputStreamReader r = new InputStreamReader(result);

仅供参考,将字符串传递给 asynctask 并在 asynctask 中进行所有转换,这将使应用程序响应速度更快。

【讨论】:

    猜你喜欢
    • 2013-02-15
    • 1970-01-01
    • 2019-10-30
    • 2012-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-12
    • 1970-01-01
    相关资源
    最近更新 更多