0

嘿,我在我的应用程序中使用 HttpUrlConnection。在我看来,每次当我打电话.getInputStream()urlConnection.getResponseCode()等时,它都会发出另一个请求,所以当我发出 POST 请求时,这对我不利。有没有办法获得某种封装响应数据并且可以从 UI 线程访问的响应对象,如下所示:

private class RegisterAsync extends AsyncTask<String, Void, HttpResponse> {

        protected String doInBackground(String... strings) {
            HttpURLConnection urlConnection = null;
            String message = null;
            try {
                URL url = new URL(REGISTER_URL);
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setDoOutput(true);
                urlConnection.setChunkedStreamingMode(0);
                OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
                out.write(strings[0].getBytes("UTF-8"));
                out.flush();
                out.close();
                HttpResponse response = urlConnection.getResponse();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                urlConnection.disconnect();
            }
            return Response;
        }

        protected void onPostExecute(HttpResponse response) {
            //Do some with response object: get status, headers, content etc?
        }
    }
4

1 回答 1

0

您可以执行以下步骤:

  1. 在单例类中创建 Web 服务调用
  2. 解析响应并将其封装在自定义对象(由您制作)中,并将解析的对象作为实例对象保存到单例中。
  3. 在此之后,您可以简单地向您的活动发送一条广播消息,让它知道已解析的数据在单例中可用
  4. 在 UI 线程上运行的onReceive()方法,因此您可以在那里快速更新您的 UI..BroadcastReceiver

实现之后,您可以在注册到将要从单例发送的意图后立即从您的活动中调用单例 Web 服务调用方法...

于 2013-06-25T15:13:32.667 回答