2011-07-14 23 views
0

我很新的流編碼,但現在我必須做更有效的Http編碼。處理Streams和ContentProducer - Java

下面是代碼,我寫的(不工作),以獲得ContentProducer爲HttpClient的:

public static ContentProducer getContentProducer(final Context context, final UUID gId) 
    { 
     return new ContentProducer() 
     { 
      public void writeTo(OutputStream outputStream) throws IOException 
      { 
       outputStream = new Base64.OutputStream(new FileOutputStream(StorageManager.getFileFromName(context, gId.toString()))); 

       outputStream.flush(); 
      } 
     }; 
    } 

我使用的Base64編碼流從這裏:http://iharder.sourceforge.net/current/java/base64/ 我的目標是使用這個功能來提供數據我從二進制文件讀取到HttpClient作爲base64編碼流。

這是我如何消費內容製作:

private MyHttpResponse processPOST(String url, ContentProducer requestData) 
    { 
     MyHttpResponse response = new MyHttpResponse(); 

     try 
     { 
      HttpPost request = new HttpPost(serviceURL + url); 
      HttpEntity entity = new EntityTemplate(requestData); 
      request.setEntity(entity); 

      ResponseHandler<String> handler = new BasicResponseHandler(); 
      response.Body = mHttpClient.execute(request, handler); 
     } 
     catch (HttpResponseException e) 
     { 

     } 
     catch (Throwable e) 
     { 

     } 

     return response; 
    } 

我有另一個ContentProducer與GSON流光作品(它的工作):

public ContentProducer getContentProducer(final Context context) 
    { 
     return new ContentProducer() 
     { 
      public void writeTo(OutputStream outputStream) throws IOException 
      { 
       Gson myGson = MyGsonWrapper.getMyGson(); 
       JsonWriter writer = new JsonWriter(new OutputStreamWriter(outputStream, "UTF-8")); 

       writer.beginObject(); 

       // stuff 

       writer.endObject(); 

       writer.flush(); 
      } 
     }; 
    } 

我的問題是:如何讓我的第一次示例工作。我做得對嗎?現在我在服務器端獲得空郵件,所以似乎沒有數據通過。

回答

1

編輯:

我認爲,問題是,你在你的ContentProviderswriteTo()方法傳遞一個OutputStream,而你用自己的OutputStream覆蓋它。該類/方法的合同可能要求您將數據寫入傳遞給您的OutputStream

基於看Android Documentation,我沒有看到一個方法可以讓你指定OutputStream使用,所以你可能只是需要寫出來的文件到OutputStream傳遞進來的數據。

相反,你應該做這樣的事情:

public void writeTo(OutputStream outputStream) throws IOException 
{ 
    byte[] buf = createByteBufferFromFile(StorageManager.getFileFromName(context, gId.toString())); 
    outputStream.write(buf); 
    outputStream.flush(); 
} 

當然,你需要提供給createByteBufferFromFile(...)的方法,我提一個實現。同樣,你應該注意,你不太可能會使用Base64 OutputStream,所以如果這是必需的,那麼你可能需要找到一種不同的方法。

+0

我應該如何修改我的第一個示例使其工作?我需要將ContentProducer與文件 – katit

+0

中的Base64流進行合併,以便更清楚地說明 - 第一個示例是我的代碼。我試圖從文件中建立base64編碼數據的生產者。 – katit

+0

那麼,你的製片人有問題嗎?如果是這樣,那麼問題是什麼?問題很少清晰時,很難提供幫助。我鼓勵你編輯這個問題,試圖給我們更多的細節,以瞭解每個代碼段的含義,你的問題是什麼,以及你嘗試過什麼...... –