当前位置: 首页 > 面试题库 >

Java:AsyncTask中嵌入的WebService询问

耿志义
2023-03-14
问题内容

。嗨,作为一名年轻的android开发人员,我正在寻找一种从服务器获取JSON响应的方法。我开始研究AsyncTask,但是每次需要询问WebService时,我都不愿意编写AsyncTask。

然后,我开始编写一个类(扩展AsyncTask),以查询一个URL(POST或GET)并提供一个包含服务器响应的回调。我想获得一些反馈,它真的有用吗?不是AsyncTask的无用覆盖,因为我一开始就想不懂。我写的越多,我就越怀疑。

预先感谢您的反馈。

这是我用来通过类查询服务器的代码:

HashMap<String, String> parameters = new HashMap<String, String>();
parameters.put("address", "sidney");
parameters.put("sensor", "false");

WebServiceAsyncTask asyncWS = new WebServiceAsyncTask(MainActivity.this);
asyncWS.setParameters(parameters);
asyncWS.execute(
        "http://maps.googleapis.com/maps/api/geocode/json",
        WebServiceAsyncTask.GET,
        new WebServiceAsyncTaskCallback() {
            @Override
            void callbackMethod(String result) {
                Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show();
            }
        }
);

这是我的WebServiceAsyncTask的代码:

import android.app.ProgressDialog;
import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Anthony Raymond
 */
public class WebServiceAsyncTask extends AsyncTask<Object, String, String> {
    public static final String GET = "GET";
    public static final String POST = "POST";

    private static final String PROGRESS_TEXT_PREPARING = "Preparing request";
    private static final String PROGRESS_PERCENT_PREPARING = "25";
    private static final String PROGRESS_TEXT_CONNECTION_SERVER = "Connecting to the server";
    private static final String PROGRESS_PERCENT_CONNECTION_SERVER = "50";
    private static final String PROGRESS_TEXT_PARSING = "Parsing received data";
    private static final String PROGRESS_PERCENT_PARSING = "75";
    private static final String PROGRESS_TEXT_END = "Process ended";
    private static final String PROGRESS_PERCENT_END = "100";


    private Context context;
    private HashMap<String, String> mData = new HashMap<String, String>();
    private ProgressDialog progressDialog;


    private WebServiceAsyncTaskCallback callbackClass;

    /**
     * If a Context is passed, a ProgressDialog will be displayed
     * NEED TO PASS Context LIKE THIS :
     * MyActivity.this
     * DO NOT USE getApplicationContext()
     * @param applicationContext
     */
    public WebServiceAsyncTask(Context applicationContext)
    {
        this.context = applicationContext;
    }

    /**
     * Create a WebServiceAsyncTask.
     * Usage : add request parameter by passing an HashMap<String, String> with the setParameter Method, then call
     * .execute(String url, WebServiceAsyncTask constant (GET or SET), WebServiceAsyncTaskCallback callback)
     * exemple :
     * HashMap<String, String> parameters = new HashMap<String, String>();
     * parameters.put("address", "Sidney");
     * parameters.put("sensor", "false");
     * WebServiceAsyncTask asyncWS = new WebServiceAsyncTask(MainActivity.this);
     * asyncWS.setParameters(parameters);
     * asyncWS.execute(
     *      "http://maps.googleapis.com/maps/api/geocode/json",
     *      WebServiceAsyncTask.GET,
     *      new WebServiceAsyncTaskCallback() {
     *          @Override
     *          void callbackMethod(String result) {
     *              Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show();
     *          }
     *      }
     * );
     */
    public WebServiceAsyncTask()
    {
        this.context = null;
    }

    private void prepareProgressDialog()
    {
        if (this.context != null)
        {
            this.progressDialog = new ProgressDialog(this.context);
            this.progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            this.progressDialog.setCancelable(true);
            this.progressDialog.setTitle("Please Wait...");
            this.progressDialog.setMessage(PROGRESS_TEXT_PREPARING);
            this.progressDialog.setProgress(Integer.parseInt(PROGRESS_PERCENT_PREPARING));
        }
    }
    private String getPostResponse(String url)
    {
        byte[] result;
        String str = "";
        HttpClient client = new DefaultHttpClient();

        HttpPost http = new HttpPost(url);
        // set up post data
        List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
        for (String key : this.mData.keySet()) {
            nameValuePair.add(new BasicNameValuePair(key, this.mData.get(key)));
        }

        UrlEncodedFormEntity urlEncodedFormEntity;
        try
        {

            urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePair);
            http.setEntity(urlEncodedFormEntity);
            this.publishProgress(PROGRESS_TEXT_CONNECTION_SERVER, PROGRESS_PERCENT_CONNECTION_SERVER);
            HttpResponse response = client.execute(http);
            StatusLine statusLine = response.getStatusLine();

            if(statusLine.getStatusCode() == HttpURLConnection.HTTP_OK)
            {
                this.publishProgress(PROGRESS_TEXT_PARSING, PROGRESS_PERCENT_PARSING);
                result  = EntityUtils.toByteArray(response.getEntity());
                str     = new String(result, HTTP.UTF_8);
            }
        }
        catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return str;
    }
    private String getGetResponse(String url)
    {
        byte[] result;
        String str = "";
        HttpClient client = new DefaultHttpClient();

        try
        {
            // set up get data and URL
            Uri.Builder uri = Uri.parse(url).buildUpon();

            for (String key : this.mData.keySet()) {
                uri.appendQueryParameter(key, this.mData.get(key));
            }

            HttpGet http = new HttpGet(String.valueOf(uri));
            this.publishProgress(PROGRESS_TEXT_CONNECTION_SERVER, PROGRESS_PERCENT_CONNECTION_SERVER);
            HttpResponse response = client.execute(http);
            StatusLine statusLine = response.getStatusLine();

            if(statusLine.getStatusCode() == HttpURLConnection.HTTP_OK)
            {
                this.publishProgress(PROGRESS_TEXT_PARSING, PROGRESS_PERCENT_PARSING);
                result  = EntityUtils.toByteArray(response.getEntity());
                str     = new String(result, HTTP.UTF_8);
            }
        }
        catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return str;
    }
    public void setParameters(HashMap<String, String> httpRequestParameters)
    {
        this.mData = httpRequestParameters;
    }



    @Override
    protected String doInBackground(Object... params)
    {
        // Ensure that we got, URL, http method and Callback
        if (params.length != 3)
        {
            this.cancel(true);
        }
        else
        {
            if ((params[2] instanceof WebServiceAsyncTaskCallback))
            {
                this.callbackClass = ((WebServiceAsyncTaskCallback)params[2]);
            }
            else
            {
                this.cancel(true);
            }
            try {
                URL url = new URL((String)params[0]);
            } catch (MalformedURLException e) {
                this.callbackClass.onError("First param must be a valid URL. (" + params[0] + " given)");
                this.cancel(true);
            }
            if (!((String)params[1]).equals(POST) && !((String)params[1]).equals(GET))
            {
                this.callbackClass.onError("Second parameters must be " + this.getClass().getName() + " POST or GET constant");
                this.cancel(true);
            }
        }

        String str          = "";

        //IS OUR REQUEST A POST
        if (params.length > 1)
        {
            if (((String)params[1]).toUpperCase().equals(WebServiceAsyncTask.POST))
            {
                str = getPostResponse(((String)params[0]));
            }
            else if(((String)params[1]).toUpperCase().equals(WebServiceAsyncTask.GET)) //THEN GET
            {
                str = getGetResponse(((String)params[0]));
            }
        }

        return str;
    }

    @Override
    protected void onPostExecute(String result)
    {
        this.mData = null;

        if (this.context != null)
        {
            this.publishProgress(PROGRESS_TEXT_END, PROGRESS_PERCENT_END);
            this.progressDialog.dismiss();
        }
        if (this.callbackClass != null)
        {
            this.callbackClass.callbackMethod(result);
        }
    }

    @Override
    protected void onPreExecute()
    {
        if (this.context != null)
        {
            this.prepareProgressDialog();
            this.progressDialog.show();
        }
    }

    @Override
    protected void onProgressUpdate(String... values) {
        if (this.context != null)
        {
            this.progressDialog.setMessage(values[0]);
            this.progressDialog.setProgress(Integer.parseInt(values[1]));
        }
    }


}

/**
 * Allow to easily get the server response
 */
abstract class WebServiceAsyncTaskCallback{
    /**
     * Return the server response as String
     * @param result server response as a String
     */
    abstract void callbackMethod(String result);

    /**
     * This method is design to report simple errors for development phase.
     * @param errMessage contains error message
     */
    protected void onError(String errMessage){};

    ;
}

问题答案:

您对AsyncTask的使用似乎很合适。如您所知..对于网络通信,您必须使用AsyncTask或您自己的线程(扩展HandlerThread。)

如果您的应用程序经常调用AsyncTask或同时执行AsyncTask,那么创建自己的线程将更加高效(所有AsyncTask请求都使用API​​
13及更高版本中的单个线程。)

我不熟悉您的应用及其功能。.您的用户是否需要对话框和状态反馈来进行这些背景网络传输?



 类似资料:
  • 我用Mongoose定义了以下模式: 我尝试执行以下查询: 查询不响应,并且从不进入回调函数。这很奇怪,因为这种类型的查询(搜索两个字符串字段)适用于我定义的另一个模式,但不适用于这个模式。另一种模式更简单,不需要任何嵌入文档。 [更新] 我试过你的建议,但不行。我认为只有两个选择: 1.我发布的模式有问题。 多谢!

  • 问题内容: 我在获取与Elasticsearch一起使用的嵌套查询时遇到问题(如果我删除了查询字符串之一,则可以使用)。我要解决的问题是我有一个包含关闭列表的文档(关闭)。我想在条件满足另一个值的闭包列表中搜索一个值。那只是从argan = 1的闭包中获得价值 我正在得到这个错误响应; 我的映射如下所示。 有人知道我在做什么错吗? 问题答案: 您的查询不是有效的查询。您需要使用适当的复合查询将其他

  • GroupIdDeliveryStatusReport的结构 如果我不能恰当地描述,请原谅我。 我就是这样写的

  • 问题内容: 我想使用ES进行图书搜索。因此,我决定将作者姓名和标题(作为嵌套文档)放入索引,如下所示: 我不明白的是:如何构造搜索查询,以便在搜索“一二”时仅找到第二本书,而在搜索“二三”时什么也找不到,而在搜索“一”时所有图书呢? 问题答案: 也许是这样的? 该查询基本上说一个文件必须有and 。您可以轻松地重新配置该查询。例如,如果您只想搜索作者,请删除嵌套部分。如果您想要另一本书,请更改嵌套

  • 问题内容: 我有一个数据库,并且使用查询来生成一个中间表,如下所示: 我想为a <avg(a)的用户计算b的标准偏差 我以这种方式计算avg(a),并且效果很好: 但是查询: 返回一个错误,更准确地说,我被告知无法识别avg中的“ a”(选择a from …)。这使我感到非常困惑,因为它可以在上一个查询中使用。 如果有人可以帮助我,我将不胜感激。 编辑: 我将查询结果存储到临时表中以生成中间表,但

  • 我正在尝试查询嵌入的文档,以获得如下结果: 文件: 我正在尝试使用SQL查询查询上述文档: 预期输出:(当我们使用位置 Id = 14 时,我们需要忽略位置 Id = 16,因为 Id = 1): 不起作用,我没有得到预期的输出,当我使用上述查询时,它给我空的结果。我如何使用嵌入文档上的where子句进行查询?