【问题标题】:Multiple http request Android多个http请求Android
【发布时间】:2015-11-11 18:59:34
【问题描述】:

在同步期间,我必须清除在线流,然后使用 HTTP 请求逐行加载所有数据。每条数据线一个请求。重要的是,http 请求按照它们创建的顺序运行。

主类:

       //Sync cloud stream
            HttpAsyncTask hats = new HttpAsyncTask();
            hats.execute(app.getProductCartStream().getClearUri());

            for(int i = 0 ; i<app.getProductCartData().size();i++){
                ArrayList<String> values = new ArrayList<String>();
                values.add(app.getProductCartData().get(i));
                String insertUri = app.getProductCartStream().getInsertUri(values);
                HttpAsyncTask hat = new HttpAsyncTask();
                hat.execute(insertUri);
            }

私人课:

private class HttpAsyncTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
    try{
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(urls[0]);
        HttpResponse httpResponse = httpClient.execute(httpGet);
        BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
        StringBuilder builder = new StringBuilder();
        for (String line = null; (line = reader.readLine()) != null; ) {
            builder.append(line).append("\n");
        }
        return builder.toString();
    }catch (Exception e) {
        Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();;
    }
    return null;
}

@Override
protected void onPostExecute(String result) {
    if(result!=null){
        Toast.makeText(getApplicationContext(), "Saved", Toast.LENGTH_LONG).show();
    }
    else{
        Toast.makeText(getApplicationContext(), "Not able to save data", Toast.LENGTH_LONG).show();
    }

}

}

问题1:请求会按照创建的顺序执行吗?即第一个 http 请求首先清除流非常重要。

问题 2:我不推荐使用的所有 HTTP 内容。现在正确的做法是什么?

问题 3:为什么我不能在 application.onDestroy() 中触发同步代码?

【问题讨论】:

    标签: android http android-asynctask


    【解决方案1】:

    Ans.1:- 是的,在 new AsyncTask().execute() 中,所有请求都按顺序处理。对于并行执行,我们调用了另一个方法。

    Ans.2:我不推荐使用的 HTTP 东西,例如 DefaultHttpClient,即使在 Android M 中它们也不存在,因此请避免使用它们并使用更好的方法:

    HttpURLConnection connection = (HttpURLConnection)url.openConnection();
    

    ...bla bla bla。

    但贬损并不意味着你的方法行不通。

    Ans3:我无法回答您的问题。

    谢谢

    【讨论】:

    • 很好,谢谢!! :) 问题 3:通过单击按钮运行我的代码效果很好。但我试图在我的应用程序文件的 onTerminate 回调中添加代码。 @Override public void onTerminate() {
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-08
    • 2011-11-22
    • 1970-01-01
    • 2018-04-10
    相关资源
    最近更新 更多