2013-06-25 49 views
0

嘿,我在我的應用程序中使用HttpUrlConnection。而且在我看來,每當我撥打.getInputStream()urlConnection.getResponseCode()等電話時,它會發出另一個請求,所以當我發出POST請求時,它對我不利。有沒有一種方法,以獲得某種響應對象它封裝響應數據,可以從UI線程,這樣的訪問:Android HttpUrlConnection響應對象

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? 
     } 
    } 
+0

你可以訪問'響應onpostExecute'這是調用UI線程 – Raghunandan

+1

是的,我說的是有沒有像HttpResponse對象? HttpUrlConnection沒有方法調用getResponse() –

+0

看看這裏,http://stackoverflow.com/questions/10684086/getting-the-response-body-of-httpresponse – QVDev

回答

0

,你可以做以下步驟:

  1. 創建Web服務在單例類中調用
  2. 解析響應並將其封裝在自定義對象(由您製作)中,並將解析對象保存到單例中作爲實例對象。
  3. 在此之後,你可以簡單地發送broadcast郵件到您的活動,讓它知道在單身
  4. 解析數據可用BroadcastReceiver在UI線程運行的onReceive()方法使您可以快速有更新UI。 。

之後你實現,你可以從你的活動您註冊將從單發送的意圖之後只需調用單Web服務調用方法...