簡體   English   中英

Android API 21異步GET請求無法正常工作

[英]Android API 21 async GET request not working

我已經實現了一個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中刪除。

謝謝!

這是一個使用HttpsUrlConnection的簡單Get Request示例:

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或Networking的樣板代碼太多,則可以嘗試使用OkHttpRetrofit類的網絡庫。

在這里,您可以找到名為OkHttp的庫的教程。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM