再利用HttpURLConnection类和AsynTask的REST请求 [英] Reuse HttpUrlConnection and AsynTask for REST requests

查看:206
本文介绍了再利用HttpURLConnection类和AsynTask的REST请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一流的PostData传输数据纬度,经度,MAC .. 到正在从服务类发送给它的服务器。在类的PostData,数据被用的辅助处理的AsyncTask HttpURLConnection类

现在我有一个新的活动,用户可以发送查询到服务器。为了达到这个我得的ArrayList<整数GT; 从服务器并创建一个类似复选框列表,用户可以选择理想的项目,则数据将被发送到服务器检索的结果。

我可以实现一个新的 Asyntask HttpURLConnection类来做到这一点还是我不得不用我的 AsynTask HttpURLConnection类 POSTDATA 类?

我AP preciate任何帮助。

我的类的PostData:

 公共类{的PostData
    串jSONString;
    私人AsyncTaskCallback回调;    公众的PostData(AsyncTaskCallback回调){
        this.callback =回调;
    }    公共字符串getjSONString(){
        返回jSONString;    }    公共无效setjSONString(字符串jSONString){
        this.jSONString = jSONString;
    }    公共无效post_data(字符串jSONString,上下文的背景下){
        this.jSONString = jSONString;        新MyAsyncTask(上下文).execute(jSONString);    }    类MyAsyncTask扩展的AsyncTask<字符串,整数的ArrayList<整数GT;> {
        最后上下文mContext;
        ArrayList的<整数GT;路线=新的ArrayList<整数GT;();
        双距离;        公共MyAsyncTask(上下文的背景下){
            mContext =背景;
        }        @覆盖
        保护的ArrayList<整数GT; doInBackground(字符串... PARAMS){
            读者的BufferedReader = NULL;            尝试{                网址myUrl =新的URL(
                        https://bustracker.rhcloud.com/webapi/test);                HttpURLConnection的康恩=(HttpURLConnection类)myUrl
                        .openConnection();
                conn.setRequestMethod(POST);
                conn.setDoOutput(真);
                conn.setConnectTimeout(10000);
                conn.setReadTimeout(10000);
                conn.setRequestProperty(内容类型,应用/ JSON);
                conn.connect();                DataOutputStream类WR =新的DataOutputStream类(
                        conn.getOutputStream());
                wr.writeBytes(PARAMS [0]);                wr.close();                StringBuilder的SB =新的StringBuilder();
                读者=新的BufferedReader(新的InputStreamReader(
                        conn.getInputStream()));
                串线;                而((行= reader.readLine())!= NULL){
                    sb.append(行+\\ n);                }                GSON GSON =新GSON();
                StopsJSON数据= gson.fromJson(sb.toString(),StopsJSON.class);                路由= data.getRoutes();
                距离= data.getDistance();
                的System.out.println(下称StringBulder的输出:
                        + sb.toString());            }赶上(IOException异常五){                e.printStackTrace();
                返回null;
            } {最后
                如果(读者!= NULL){
                    尝试{
                        reader.close();
                        返回null;
                    }赶上(例外五){
                        e.printStackTrace();
                    }
                }
            }            返回null;        }        保护无效onPostExecute(ArrayList的<整数GT;的结果){             如果(路径=空&放大器;!&放大器;!routes.isEmpty()){
            callback.onAsyncTaskFinished(路线,距离);
             }其他{
                 Log.e(123,避免空指针,路线都为空!);
             }
        }    }}


解决方案

这可能会设置你一些code重构的路径上,但关于REST总体上是好的做法要求你应该考虑的排球,或的改造,(也另一SO质疑关于改造,这可能有助于)。

这些库都是非常高效的性能,明智的,并且从长远来看,会为你节省很多痛苦,他们照顾后台线程,你不一定需要明确使用HttpURLConnection类。

希望这有助于。

修改

要进一步回答你的问题 - 如果你想专门使用的AsyncTask - 您使用的PostData类为通用类,你的情况为网络操作(也有可能会想使它成为一个单身,并给它一个更一般的名称)。

和是您的实现看起来你应该能够使用它,\\修改\\补充应在AsyncTask的本身的PostData下,无需另一类通用提出,如果需要的任何修改 - 你可以添加更多内AsyncTask的子类。

我(非常非常一般)方向将是:

 公共类NetworkData {
串jSONString;
私人AsyncTaskCallback回调;公共NetworkData(AsyncTaskCallback回调){
    this.callback =回调;
}公共字符串getjSONString(){
    返回jSONString;}公共无效setjSONString(字符串jSONString){
    this.jSONString = jSONString;
}//让我们说这是POST请求...
公共无效POSTDATA(字符串jSONString,上下文的背景下){
    this.jSONString = jSONString;    新MyPostTask(上下文).execute(jSONString);}//让我们说这是GET请求...
公共无效的getData(字符串jSONString,上下文的背景下){
    this.jSONString = jSONString;    新MyGetTask(上下文).execute(jSONString);}类MyPostTask扩展的AsyncTask<字符串,整数的ArrayList<整数GT;> {
    最后上下文mContext;
    ArrayList的<整数GT;路线=新的ArrayList<整数GT;();
    双距离;    公共MyPostTask(上下文的背景下){
        mContext =背景;
    }    @覆盖
    保护的ArrayList<整数GT; doInBackground(字符串... PARAMS)
    {
        尝试
        {
         //你的东西POST请求...
        }赶上(IOException异常E)
        {
         // ...
        }
        最后
            {
             // ...
            }
        }
     }类MyGetTask扩展的AsyncTask<弦乐,无效的ArrayList<对象>> {
    最后上下文mContext;
    ArrayList的<对象>路线=新的ArrayList<对象>();    公共MyPostTask(上下文的背景下){
        mContext =背景;
    }    @覆盖
    保护的ArrayList<对象> doInBackground(字符串... PARAMS)
    {
        尝试
        {
         //你的东西GET请求...
        }
        赶上(IOException异常E)
        {
         // ...
        }
        最后
        {
         // ...
        }
      }
    }
}

如果你选择使用排或改造,然后继续使用通用类结构,只需要修改它的公用事业和更换requset格式(即的,而不是AsyncTask的部分)。

I have PostData class to transmit data lat, long,mac,.. to the server which is being sent to it from the service class. In PostData class, the data is being processed with the aid of AsyncTask and HttpURLConnection.

Now I have a new activity where the user can send query to the server. To reach that I have to get ArrayList<Integer> from the server and create a something like checkbox list, where the user can select the desirable items then the data will be sent to the server to retrieve a result.

Can I implement a new Asyntask and HttpURLConnection to achieve that or I have to use my AsynTask and HttpURLCOnnection in the POstData class?

I appreciate any help.

My PostData class:

public class PostData {
    String jSONString;
    private AsyncTaskCallback callback;

    public PostData(AsyncTaskCallback callback) {
        this.callback = callback;
    }

    public String getjSONString() {
        return jSONString;

    }

    public void setjSONString(String jSONString) {
        this.jSONString = jSONString;
    }

    public void post_data(String jSONString, Context context) {
        this.jSONString = jSONString;

        new MyAsyncTask(context).execute(jSONString);

    }

    class MyAsyncTask extends AsyncTask<String, Integer, ArrayList<Integer>> {
        final Context mContext;
        ArrayList<Integer> routes = new ArrayList<Integer>();
        double distance;

        public MyAsyncTask(Context context) {
            mContext = context;
        }

        @Override
        protected ArrayList<Integer> doInBackground(String... params) {
            BufferedReader reader = null;

            try {

                URL myUrl = new URL(
                        "https://bustracker.rhcloud.com/webapi/test");

                HttpURLConnection conn = (HttpURLConnection) myUrl
                        .openConnection();
                conn.setRequestMethod("POST");
                conn.setDoOutput(true);
                conn.setConnectTimeout(10000);
                conn.setReadTimeout(10000);
                conn.setRequestProperty("Content-Type", "application/json");
                conn.connect();

                DataOutputStream wr = new DataOutputStream(
                        conn.getOutputStream());
                wr.writeBytes(params[0]);

                wr.close();

                StringBuilder sb = new StringBuilder();
                reader = new BufferedReader(new InputStreamReader(
                        conn.getInputStream()));
                String line;

                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");

                }

                Gson gson = new Gson();
                StopsJSON data = gson.fromJson(sb.toString(), StopsJSON.class);

                routes = data.getRoutes();
                distance = data.getDistance();
                System.out.println("The output of the StringBulder: "
                        + sb.toString());

            } catch (IOException e) {

                e.printStackTrace();
                return null;
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                        return null;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            return null;

        }

        protected void onPostExecute(ArrayList<Integer> result) {

             if (routes != null && !routes.isEmpty()) {
            callback.onAsyncTaskFinished(routes, distance);
             }else{
                 Log.e("123", "Avoiding null pointer, the routes are null!!!");
             }
        }

    }

}

解决方案

This may set you on a path of some code refactoring, but for general good practice regarding REST requests you should look into Volley, or Retrofit, (also another SO question regarding retrofit that might help).

these libraries are very efficient performance-wise, and in the long run will save you a lot of grief, they take care of the background threading, and you won't necessarily need to explicitly use HttpUrlConnection.

Hope this helps.

Edit :

To further answer your question - if you do wish to specifically use AsyncTask - you should use the PostData class as a general purpose class, in your case for the network operations (might also possibly want to make it a Singleton, and give it a more general name).

and yes your implementation looks like you should be able to use it, and any corrections\changes\additions should be made in the AsyncTask itself under PostData, no need for another general class, if need be - you can just add more inner AsyncTask subclasses.

my (very very general) direction would be:

public class NetworkData {
String jSONString;
private AsyncTaskCallback callback;

public NetworkData(AsyncTaskCallback callback) {
    this.callback = callback;
}

public String getjSONString() {
    return jSONString;

}

public void setjSONString(String jSONString) {
    this.jSONString = jSONString;
}

//let's say this is for post requests...
public void postData(String jSONString, Context context) {
    this.jSONString = jSONString;

    new MyPostTask(context).execute(jSONString);

}

//let's say this is for get requests...
public void getData(String jSONString, Context context) {
    this.jSONString = jSONString;

    new MyGetTask(context).execute(jSONString);

}

class MyPostTask extends AsyncTask<String, Integer, ArrayList<Integer>> {
    final Context mContext;
    ArrayList<Integer> routes = new ArrayList<Integer>();
    double distance;

    public MyPostTask(Context context) {
        mContext = context;
    }

    @Override
    protected ArrayList<Integer> doInBackground(String... params) 
    {
        try
        {
         //do you stuff for post requests...
        } catch (IOException e) 
        {
         //...
        } 
        finally 
            {
             //...
            }
        }
     }

class MyGetTask extends AsyncTask<String, Void, ArrayList<Object>> {
    final Context mContext;
    ArrayList<Object> routes = new ArrayList<Object>();

    public MyPostTask(Context context) {
        mContext = context;
    }

    @Override
    protected ArrayList<Object> doInBackground(String... params) 
    {
        try
        {
         //do you stuff for get requests...
        } 
        catch (IOException e) 
        {
         //...
        } 
        finally 
        {
         //...
        }
      }
    }
}

If you do choose to use Volley or Retrofit, then keep using the general class structure and just modify it's utilities and replace the requset format (i.e. instead of the AsyncTask parts).

这篇关于再利用HttpURLConnection类和AsynTask的REST请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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