如何添加代码以等待响应?

时间:2017-03-22 12:27:56

标签: java android servlets android-asynctask

我想知道如何在转到onPostExecute()方法之前等待来自servlet的响应。

请提供解决方案。

编辑:编辑版本

Response responsed = null;

    @Override
    protected String doInBackground(String... strings) {
        ArrayList<Farm> farmSend= dbFarm.getAllFarms();

        String result = "";
        OkHttpClient client = new OkHttpClient();
        RequestBody postRequestBody = new FormBody.Builder()
                .add("farms", new Gson().toJson(farmSend))
                .add("dataToBeRetrieved", "getData")
                .build();

        Request request = new Request.Builder()
                .url(new ipconfig().getIp() + "MobileFarm")
                .post(postRequestBody)
                .build();

            try {
                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);

                        responsed = response;
                        Headers responHeaders = response.headers();
                        for (int i = 0, size = responHeaders.size(); i < size; i++) {
                            Log.i("response: ", responHeaders.name(i) + ": " + responHeaders.value(i));
                        }
                        Log.i("response body: ", response.body().toString());
                    }
                });
                result = responsed.body().string();
            } catch (IOException e) {
                e.printStackTrace();
            }
        return result;
    }

编辑:这是我的servlet代码。

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int addCount = 0;
        int updateCount = 0;

        System.out.println("farmer input form mobile upload");
        ArrayList<Farmer> farmers = new Gson().fromJson(request.getParameter("farmers"), new TypeToken<List<Farmer>>() {
        }.getType());
        for (int a = 0; a < farmers.size(); a++) {
            if (a < new FarmerDAO().getListOfFarmers().size()) {
                if (new FarmerDAO().updateFarmer(farmers.get(a))) {
                    updateCount++;
                }
            } else if (new FarmerDAO().registerFarmer(farmers.get(a))) {
                addCount++;
            } else {
                System.out.println(farmers.get(a).getFarmerID() + " not added/updated");
            }
        }
        System.out.println("farmer input count updated: " + updateCount);
        System.out.println("farmer input count added: " + addCount);

        response.getWriter().write(new Gson().toJson("farmer input completed"));
    }

立即打印的唯一内容是“来自移动上传的农民输入”和“开始循环”。在收到任何回复之前,不会打印后续的打印行。

2 个答案:

答案 0 :(得分:0)

使用okhttp提供的这些回调:

client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {

        }

        @Override
        public void onResponse(Response response) throws IOException {

        }
    });

答案 1 :(得分:0)

您可以使用图书馆本身的Asynchronous Get,只要有响应,就可以使用Callback

来自他们的文档

  

在工作线程上下载文件,并在响应可读时回调。回调是在响应头准备好之后进行的。阅读响应正文可能仍会阻止。 OkHttp目前不提供异步API来接收部分响应主体。

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

来源:https://github.com/square/okhttp/wiki/Recipes