【问题标题】:Android: Implementing a reusable HTTP Async MethodAndroid:实现可重用的 HTTP 异步方法
【发布时间】:2013-04-23 15:31:02
【问题描述】:

我一直在搜索,但没有找到任何方法的实现,该方法允许发出 HTTP 发布请求,同时接收 URL 和数据作为函数的参数。

我的意思是,我找到的所有示例都是为一组特定的参数量身定制的,我需要在 AsyncTask 方法中获取一个 URL 和一个包含数据的数组,但是如何传递 url(字符串)参数和发布数据(数组)参数?

任何帮助或链接将不胜感激。

【问题讨论】:

标签: android post methods android-asynctask code-reuse


【解决方案1】:

我对类似情况使用以下模式:

import java.util.List;
import org.apache.http.NameValuePair;
import android.os.AsyncTask;

public class AsyncHttpPostTask extends AsyncTask<Void, Void, Boolean> {

    private List<NameValuePair> httpPostParams;
    private String postHref;
    private String someOtherValue;

    public AsyncHttpPostTask(final String postHref, final List<NameValuePair> httpPostParams, final String someOtherValue) {
        super();
        this.postHref = postHref;
        this.httpPostParams = httpPostParams;
        this.someOtherValue = someOtherValue;
    }

    @Override
    protected Boolean doInBackground(final Void... params) {
        // Use httpPostParams (or any other values you supplied to a constructor) in your actual Http post here
        // ...
        return true;
    }
}

要使用 AsyncTask,请创建一个实例,为构造函数和调用 execute() 提供所需的参数:

new AsyncHttpPostTask("http://example.com/post", httpPostParams, otherValue).execute();

【讨论】:

    猜你喜欢
    • 2015-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-09
    • 1970-01-01
    • 1970-01-01
    • 2011-11-20
    相关资源
    最近更新 更多