Java的:一个WebService问镶嵌着一个AsyncTask的 [英] Java : a WebService asking embeded in a AsyncTask

查看:102
本文介绍了Java的:一个WebService问镶嵌着一个AsyncTask的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

。作为一个年轻的Andr​​oid开发者我一直在寻找一种方式来获得从服务器的JSON响应。 我开始看的AsyncTask,但C时的AsyncTask每次我需要问一个WebService我不舒服的感觉,以$ C $。

然后,我开始codeA类(扩展AsyncTask的),其查询的URL(POST或GET),并提供包含从服务器的响应回调。 我想有一些反馈,是不是真的有用,而不是一个的AsyncTask的无用的叠加,因为我错过了了解一些在开始。 我越code吧,我越怀疑。

在此先感谢您的反馈。

这里的codeI用于查询服务器,我的课:

的HashMap<字符串,字符串>参数=新的HashMap<字符串,字符串>(); parameters.put(地址,悉尼); parameters.put(传感器,假); WebServiceAsyncTask asyncWS =新WebServiceAsyncTask(MainActivity.this); asyncWS.setParameters(参数); asyncWS.execute(         http://maps.googleapis.com/maps/api/geo$c$c/json         WebServiceAsyncTask.GET,         新WebServiceAsyncTaskCallback(){             @覆盖             无效callbackMethod(字符串结果){                 Toast.makeText(getApplicationContext(),结果,Toast.LENGTH_SHORT).show();             }         } );

下面是我的WebServiceAsyncTask的code:

进口android.app.ProgressDialog; 进口android.content.Context; 进口android.net.Uri; 进口android.os.AsyncTask; 进口org.apache.http.Htt presponse; 进口org.apache.http.NameValuePair; 进口org.apache.http.StatusLine; 进口org.apache.http.client.HttpClient; 进口org.apache.http.client.entity.UrlEn codedFormEntity; 进口org.apache.http.client.methods.HttpGet; 进口org.apache.http.client.methods.HttpPost; 进口org.apache.http.impl.client.DefaultHttpClient; 进口org.apache.http.message.BasicNameValuePair; 进口org.apache.http.protocol.HTTP; 进口org.apache.http.util.EntityUtils; 进口java.io.UnsupportedEncodingException; 进口java.net.HttpURLConnection中; 进口java.net.MalformedURLException; 进口的java.net.URL; 进口的java.util.ArrayList; 进口的java.util.HashMap; 进口的java.util.List; / **  *安东尼·雷蒙德  * / 公共类WebServiceAsyncTask扩展的AsyncTask<对象,字符串,字符串> {     公共静态最后弦乐GET =GET;     公共静态最后弦乐POST =POST;     私有静态最后弦乐PROGRESS_TEXT_ prePARING =preparing要求;     私有静态最后弦乐PROGRESS_PERCENT_ prePARING =25;     私有静态最后弦乐PROGRESS_TEXT_CONNECTION_SERVER =连接到服务器;     私有静态最后弦乐PROGRESS_PERCENT_CONNECTION_SERVER =50;     私有静态最后弦乐PROGRESS_TEXT_PARSING =分析接收到的数据;     私有静态最后弦乐PROGRESS_PERCENT_PARSING =75;     私有静态最后弦乐PROGRESS_TEXT_END =结束进程;     私有静态最后弦乐PROGRESS_PERCENT_END =100;     私人上下文的背景下;     私人的HashMap<字符串,字符串> MDATA =新的HashMap<字符串,字符串>();     私人ProgressDialog progressDialog;     私人WebServiceAsyncTaskCallback callbackClass;     / **      *如果上下文传递,一个ProgressDialog将显示      *需要通过上下文是这样的:      * MyActivity.this      *请勿使用getApplicationContext()      * @参数的applicationContext      * /     公共WebServiceAsyncTask(上下文的applicationContext)     {         this.context =的applicationContext;     }     / **      *创建WebServiceAsyncTask。      *使用方法:通过传递添加请求参数中的HashMap<字符串,字符串>与通过setParameter方法​​,然后调用      * .execute(字符串URL,WebServiceAsyncTask常数(获取或设置),WebServiceAsyncTaskCallback回调)      *为例:      * HashMap的<字符串,字符串>参数=新的HashMap<字符串,字符串>();      * parameters.put(地址,悉尼);      * parameters.put(传感器,假);      * WebServiceAsyncTask asyncWS =新WebServiceAsyncTask(MainActivity.this);      * asyncWS.setParameters(参数);      * asyncWS.execute(      *http://maps.googleapis.com/maps/api/geo$c$c/json      * WebServiceAsyncTask.GET,      *新WebServiceAsyncTaskCallback(){      * @覆盖      *无效callbackMethod(字符串结果){      * Toast.makeText(getApplicationContext(),结果,Toast.LENGTH_SHORT).show();      *}      *}      *);      * /     公共WebServiceAsyncTask()     {         this.context = NULL;     }     私人无效prepareProgressDialog()     {         如果(this.context!= NULL)         {             this.progressDialog =新ProgressDialog(this.context);             this.progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);             this.progressDialog.setCancelable(真正的);             this.progressDialog.setTitle(请稍候...);             this.progressDialog.setMessage(PROGRESS_TEXT_ prePARING);             this.progressDialog.setProgress(的Integer.parseInt(PROGRESS_PERCENT_ prePARING));         }     }     私人字符串getPostResponse(字符串URL)     {         byte []的结果;         字符串str =;         HttpClient的客户端=新DefaultHttpClient();         HttpPost HTTP =新HttpPost(URL);         //设置了POST数据         名单<的NameValuePair>的NameValuePair =新的ArrayList<的NameValuePair>();         对于(字符串键:this.mData.keySet()){             nameValuePair.add(新BasicNameValuePair(键,this.mData.get(键)));         }         UrlEn codedFormEntity urlEn codedFormEntity;         尝试         {             urlEn codedFormEntity =新UrlEn codedFormEntity(的NameValuePair);             http.setEntity(urlEn codedFormEntity);             this.publishProgress(PROGRESS_TEXT_CONNECTION_SERVER,PROGRESS_PERCENT_CONNECTION_SERVER);             HTT presponse响应= client.execute(HTTP);             状态行状态行= response.getStatusLine();             如果(statusLine.getStatus code()== HttpURLConnection.HTTP_OK)             {                 this.publishProgress(PROGRESS_TEXT_PARSING,PROGRESS_PERCENT_PARSING);                 结果= EntityUtils.toByteArray(response.getEntity());                 海峡=新的字符串(结果,HTTP.UTF_8);             }         }         赶上(UnsupportedEncodingException E)         {             e.printStackTrace();         }         赶上(例外五)         {             e.printStackTrace();         }         返回海峡;     }     私人字符串getGetResponse(字符串URL)     {         byte []的结果;         字符串str =;         HttpClient的客户端=新DefaultHttpClient();         尝试         {             //设置获取数据和URL             Uri.Builder URI = Uri.parse(URL).buildUpon();             对于(字符串键:this.mData.keySet()){                 uri.appendQueryParameter(键,this.mData.get(键));             }             HTTPGET HTTP =新HTTPGET(将String.valueOf(URI));             this.publishProgress(PROGRESS_TEXT_CONNECTION_SERVER,PROGRESS_PERCENT_CONNECTION_SERVER);             HTT presponse响应= client.execute(HTTP);             状态行状态行= response.getStatusLine();             如果(statusLine.getStatus code()== HttpURLConnection.HTTP_OK)             {                 this.publishProgress(PROGRESS_TEXT_PARSING,PROGRESS_PERCENT_PARSING);                 结果= EntityUtils.toByteArray(response.getEntity());                 海峡=新的字符串(结果,HTTP.UTF_8);             }         }         赶上(UnsupportedEncodingException E)         {             e.printStackTrace();         }         赶上(例外五)         {             e.printStackTrace();         }         返回海峡;     }     公共无效setParameters(HashMap的<字符串,字符串> HTT prequestParameters)     {         this.mData = HTT prequestParameters;     }     @覆盖     保护字符串doInBackground(对象... PARAMS)     {         //确保我们得到,URL,HTTP方法和回调         如果(params.length!= 3)         {             this.cancel(真正的);         }         其他         {             如果((PARAMS [2]的instanceof WebServiceAsyncTaskCallback))             {                 this.callbackClass =((WebServiceAsyncTaskCallback)PARAMS [2]);             }             其他             {                 this.cancel(真正的);             }             尝试 {                 网址URL =新的URL((字符串)PARAMS [0]);             }赶上(MalformedURLException异常E){                 this.callbackClass.onError(第一个参数必须是一个有效的URL(+参数[0] +表示));                 this.cancel(真正的);             }             如果(!((字符串)PARAMS [1])等于(POST)及。&安培;!((字符串)PARAMS [1])等于(GET))             {                 this.callbackClass.onError(第二个参数必须是+ this.getClass()的getName()+POST或GET恒);                 this.cancel(真正的);             }         }         字符串str =;         //就是我们的要求一个POST         如果(params.length→1)         {             如果(((字符串)PARAMS [1])。与toUpperCase()。等于(WebServiceAsyncTask.POST))             {                 海峡= getPostResponse(((字符串)PARAMS [0]));             }             否则,如果(((字符串)PARAMS [1])。与toUpperCase()。等于(WebServiceAsyncTask.GET))//然后得到             {                 海峡= getGetResponse(((字符串)PARAMS [0]));             }         }         返回海峡;     }     @覆盖     保护无效onPostExecute(字符串结果)     {         this.mData = NULL;         如果(this.context!= NULL)         {             this.publishProgress(PROGRESS_TEXT_END,PROGRESS_PERCENT_END);             this.progressDialog.dismiss();         }         如果(this.callbackClass!= NULL)         {             this.callbackClass.callbackMethod(结果);         }     }     @覆盖     在preExecute保护无效()     {         如果(this.context!= NULL)         {             这prepareProgressDialog();             this.progressDialog.show();         }     }     @覆盖     保护无效onProgressUpdate(字符串...值){         如果(this.context!= NULL)         {             this.progressDialog.setMessage(值[0]);             this.progressDialog.setProgress(的Integer.parseInt(值[1]));         }     } } / **  *允许轻松获取服务器响应  * / 抽象类WebServiceAsyncTaskCallback {     / **      *返回服务器的响应为String      * @参数因此服务器响应作为一个字符串      * /     抽象无效callbackMethod(字符串结果);     / **      *此方法设计报告的发展阶段简单的错误。      * @参数errMessage包含错误信息      * /     保护无效的onError(字符串errMessage){};     ; }

解决方案

您使用的AsyncTask的似乎是合适的。正如你可能知道。对于网络通信必须使用的AsyncTask或您自己的线程(延长HandlerThread。)

如果您的应用程序频繁调用的AsyncTask或执行同时的AsyncTask然后创建你自己的线程会更有效率(所有AsyncTask的请求使用一个线程API 13以上。)

我不熟悉你的应用程序,以及它是如何发挥作用......做你的用户需要在对话框和状态反馈thses后台网络传输?

. Hi, as a young android developer i was looking at a way to get a JSON response from a server. I started looking at AsyncTask but i not feeling comfortable to code an AsyncTask for each time i needed to ask a WebService.

Then i started to code a class (extends AsyncTask) that query an URL (POST or GET) and provide a callback containing the response from the server. I wanted to have some feedback, is it really useful, and not an useless overlay of an AsyncTask cause i missed understand something at the beginning. The more i code it, the more i doubt.

Thanks in advance for your feedback.

Here's the code i use to query a server with my class :

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();
            }
        }
);

Here's the code of my 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){};

    ;
}

解决方案

Your use of AsyncTask appears appropriate. As you may be aware.. for network communications you must use AsyncTask or your own thread (extend HandlerThread.)

If your app is frequently calling AsyncTask or is executing simultaneous AsyncTask then creating your own thread will be more efficient (all AsyncTask requests use a single thread in API 13 and up.)

I'm unfamiliar with your app and how it functions.. do your users require the dialogs and status feedback for thses background network transmissions?

这篇关于Java的:一个WebService问镶嵌着一个AsyncTask的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆