【问题标题】:Android API 21 async GET request not workingAndroid API 21 异步 GET 请求不起作用
【发布时间】:2016-07-21 21:06:57
【问题描述】:

我已经实现了一个 Android 应用,到目前为止还没有遇到任何问题。

但是让一个异步 GET 请求工作大约花了我 3 天的时间,仍然没有进展。

我尝试使用 Android 文档并编写了一些代码.. 没有结果 然后我尝试了几乎所有在线解决方案..再次没有结果

能否请您提供针对 Android API 级别 21 中的异步 GET 请求的解决方案?

    getRequest task = new getRequest();
    String contents = null;

    try {
        contents = task.execute(url).get();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }

这是我的课

public static class getRequest extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {
        String result = "";
        URL url;
        HttpURLConnection urlConnection;

        try {
            url = new URL(params[0]);
            urlConnection = (HttpURLConnection) url.openConnection();

            urlConnection.setRequestMethod("GET");
            urlConnection.setRequestProperty("headerFieldName", "I took out the fields here since they were personal");

            InputStream in = urlConnection.getInputStream();
            InputStreamReader reader = new InputStreamReader(in);

            int data = reader.read();

            while (data != -1) {
                result += (char) data;
                data = reader.read();
            }

            return result;
        } catch(Exception e) {
            e.printStackTrace();

            return "Failed";
        }
    }
}

我也尝试使用 org.apache,但该库已从 API 级别 23 中删除。

谢谢!

【问题讨论】:

  • 请贴一些代码!让我们看看您到目前为止拥有什么,我们会更轻松地为您提供帮助。
  • @TodorKostov 刚刚添加了代码,谢谢!

标签: java android asynchronous httprequest


【解决方案1】:

这里是一个使用HttpsUrlConnection 的简单获取请求示例:

try {
    URL url = new URL(your_url_address);
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    try {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
        StringBuilder stringBuilder = new StringBuilder();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            stringBuilder.append(line);
        }
        bufferedReader.close();

        //Parse Response
        JSONObject jsonObject = new JSONObject(stringBuilder.toString());

    } finally {
        urlConnection.disconnect();
    }
} catch(Exception e) {
    Log.e("ERROR", e.getMessage(), e);
}

如果AsyncTask 或一般网络的样板代码过多,您可以尝试使用OkHttpRetrofit 等网络库。

【讨论】:

    【解决方案2】:

    Here你可以找到一个名为 OkHttp 的库的教程。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      • 2018-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-30
      相关资源
      最近更新 更多