【问题标题】:Alternative way than AsyncTask to send data to server将数据发送到服务器的 AsyncTask 之外的替代方法
【发布时间】:2016-09-15 16:19:46
【问题描述】:

我想确定我下面的代码是否有更好的方法,一种将数据发送到下面的服务器的方法是否有效,但可以更好吗?

class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... params) {

        String json = "";
        String s_calc=String.valueOf(calc);;


        try {
            RequestBody formBody = new FormEncodingBuilder()
                    //  .add("tag","login")
                    .add("likes", "9")
                    .add("id", id)
                    .build();
            Request request = new Request.Builder()
                    .url("http://justedhak.com/old-files/singleactivity.php")
                    .post(formBody)
                    .build();
            Response responses = null;
            try {
                responses = client.newCall(request).execute();
            } catch (IOException e) {
                e.printStackTrace();
            }
            String jsonData = responses.body().string();
            JSONObject Jobject = new JSONObject(jsonData);

            int success = Jobject.getInt("success");
            if (success == 1) {
                // this means that the credentials are correct, so create a login session.
                JSONArray JAStuff = Jobject.getJSONArray("stuff");
                int intStuff = JAStuff.length();
                if (intStuff != 0) {
                    for (int i = 0; i < JAStuff.length(); i++) {
                        JSONObject JOStuff = JAStuff.getJSONObject(i);
                        //create a login session.
                   //     session.createLoginSession(name, pass);
                    }
                }

            } else {
                // return an empty string, onPostExecute will validate the returned value.
                return "";
            }

        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            Log.e("MYAPP", "unexpected JSON exception", e);
        }

        //this return will be reached if the user logs in successfully. So, onPostExecute will validate this value.
        return "RegisterActivity success";
    }


    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        // if not empty, this means that the provided credentials were correct. .
        if (!result.equals("")) {
            finish();
            return;
        }
        //otherwise, show a popup.
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(SingleObjectActivity.this);
        alertDialogBuilder.setMessage("Wrong username or password, Try again please.");
    //    alertDialogBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
      //      @Override
        //    public void onClick(DialogInterface arg0, int arg1) {
          //      alertDialog.dismiss();
         //   }
       // });
       // alertDialog = alertDialogBuilder.create();
       // alertDialog.show();
    }
}

【问题讨论】:

  • 它类似于 okttp 对吧? @KenWolf
  • Retrofit 使用 OKHttp 作为 http 客户端
  • 定义“更好”
  • @njzk2 最佳实践,良好的表现,良好的行为......

标签: android


【解决方案1】:

“更好”是主观的,但正如@KenWolf 指出的那样,我相信普遍的共识是Retrofit 是访问服务器API 的方式。 Retrofit 依赖于OkHttp,可以使用多种converters 为你解析JSON(包括Gson,以及我的偏好Moshi)。它也是compatibleRxJava(和RxAndroid),可以改变世界。

Retrofit 的替代方案是由 Google 提供的 Volley,尽管它的抽象级别要低得多。另外,谷歌没有出过Retrofit有的类似的支持库,只支持Gson进行反序列化。

【讨论】:

  • @cricket_007 就什么而言? Google 确实维护了 select languages 的协议缓冲区 API,但没有维护任何与 RetrofitVolley 兼容的库。 Square 确实为 Retrofit 维护了一个 ProtoBuf 库。
  • @Moudiz 我发布的Retrofit 链接将指导您完成设置并提供一些基本示例。 GitHub repo 也提供样本。至于序列化和反序列化,大多数(如果不是全部)也在其存储库中提供示例。 u2020 也是 Jake Wharton 制作的一个很棒的示例应用程序,它同时使用了 RetrofitMoshiRxAndroid,以及用于依赖注入的 Dagger
  • 我只是指出关于谷歌只支持 Gson 的评论,但 ProtoBuf 也是另一种选择
【解决方案2】:

您已经在使用 OkHttp。所以,你甚至不需要 AsyncTask

OKHttp Recipes - Async GET 可以在 AsyncTask 之外使用。如果您明确使用 JSON 请求,那么 Retrofit 或 Volley 是不错的选择。

private final OkHttpClient client = new OkHttpClient();

  public void run() throws Exception {
    Request request = new Request.Builder()
        .url("http://publicobject.com/helloworld.txt")
        .build();

    client.newCall(request).enqueue(new Callback() {
      @Override public void onFailure(Call call, IOException e) {
        e.printStackTrace();
      }

      @Override public void onResponse(Call call, Response response) throws IOException {
        if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

        Headers responseHeaders = response.headers();
        for (int i = 0, size = responseHeaders.size(); i < size; i++) {
          System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
        }

        System.out.println(response.body().string());
      }
    });
  }

【讨论】:

  • 我遇到了与图像和缓存相关的凌空问题,我不记得了,所以使用 okhttp 不需要使用 asyntask 对吗?
  • 可能有必要的时候,但我现在想不出来
  • @cricket_007 我遇到错误“无法解析回调”,我没有为它导入哪个..你想要错误的屏幕截图吗?他们在文档中提到了导入或任何内容
  • @Bryan 确实很少有合法的情况下使用 asynctask 仍然是一个不错的选择。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-27
  • 2014-03-22
  • 1970-01-01
  • 1970-01-01
  • 2010-12-29
相关资源
最近更新 更多