繁体   English   中英

处理一些网络请求的正确方法

[英]The right way to deal with a few network requests

我在Java / Android中很陌生。 我正在编写android应用,该应用从在线api获取数据。 问题是,我不确定我的概念是否正确。 因此,我的应用发送了第一个请求,但是我需要一些响应数据才能启动下一个请求。

这或多或少是一些示例,现在看起来如何:

public class MainActivity extends AppCompatActivity{
    private int key = 0;

    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        new DownloadTask().execute("url of 1st request");
    }

    private class DownloadTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            try {
                return downloadContent(params[0]);
            } catch (IOException e) {
                return "Unable to retrieve data. URL may be invalid.";
            }
        }

        @Override
        protected void onPostExecute(String result) {
           if(key == 0){

               // I know it's 1st request because my key == 0

               JSONObject json = new JSONObject(result);
               String id = json.getString("id");
               key++;
               new DownloadTask().execute( "url of 2nd request/" + id );
           }else{

               // I know it's 2st request because my key != 0

               //here I'm getting data i need

               // and I'm going to rest of my app
               end(result);
           }
        }
    }

    private void end(String result){
        //rest of my app
    }

}

代码工作正常,但是我想知道这是否是正确的方法。 也许您知道执行此操作的另一种方法,但我并不是要求提供完整的新代码,而是可能应该找到并阅读一些主题。

如果您想异步执行此操作,我建议您使用CompletableFuture的。 它非常简单,看起来像这样:

CompletableFuture
                    .supplyAsync(() -> yourFirstrequest())
                    .thenApplyAsync(yourInstance::getResponse)
                    .thenAcceptAsync(nextRequestClass::sendNextrequest);

或者您也可以按Future将它们分开,例如:

CompletableFuture firstRequest =  CompletableFuture.supplyAsync(() -> yourFirstrequest());
CompletableFuture getResponse = firstRequest.thenApply(response -> someActionWithResponse(response));

它是非常强大且方便的框架。 看一下Java文档Android特定文档

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM