2015-07-10 116 views
1

基本上我一直在使用這些特定的代碼行很長一段時間,從來沒有遇到過問題。沒有什麼是被感動,但現在我越來越HTTP請求 - 已連接

IllegalStateException異常 - 已經連接

正是之後我設置conn.setUsesCaches(false)

public void PutImageToS3(String signedUrl, Bitmap image) throws WampNetworkException, IOException { 
      URL url = new URL(signedUrl); 
      HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
      conn.getDoOutput(); 
      conn.setUseCaches(false); 
      conn.setRequestMethod("PUT"); 
      conn.addRequestProperty("Content-Type", "image/jpeg"); 
      conn.addRequestProperty("Connection", "close"); 
      OutputStream out = new BufferedOutputStream(conn.getOutputStream()); 
      image.compress(Bitmap.CompressFormat.JPEG, 100, out); 

      if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) { 
       throw new IOException("Failed to upload image to S3: " 
         + conn.getResponseCode() + conn.getResponseMessage() + "\r\n"); 
      } 
      out.flush(); 
      out.close(); 
      conn.disconnect(); 
     } 
+0

在發佈問題時,您應始終共享打印堆棧跟蹤。 – Rajesh

回答

0

寫代碼try-finally塊,然後嘗試

public void PutImageToS3(String signedUrl, Bitmap image) throws WampNetworkException, IOException { 

     try{ 
     URL url = new URL(signedUrl); 
     HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
     conn.getDoOutput(); 
     conn.setUseCaches(false); 
     conn.setRequestMethod("PUT"); 
     conn.addRequestProperty("Content-Type", "image/jpeg"); 
     conn.addRequestProperty("Connection", "close"); 
     OutputStream out = new BufferedOutputStream(conn.getOutputStream()); 
     image.compress(Bitmap.CompressFormat.JPEG, 100, out); 

     if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) { 
      throw new IOException("Failed to upload image to S3: " 
        + conn.getResponseCode() + conn.getResponseMessage() + "\r\n"); 
     } 
    } 
    finally{ 
     out.flush(); 
     out.close(); 
     conn.disconnect(); 
     } 
    } 
+0

沒有什麼改變 – Alex

+0

嘗試刪除後,如果拋出異常 –

+0

仍然不工作 – Alex

0

你需要寫請求之前獲取響應碼。

getResponseCode()之前移動close(),並刪除多餘的flush()

NB你爲什麼打電話getDoOutput()而忽略結果?

+0

我沒有結果,它是一個put函數,只是上傳一張圖片。但我也沒有設置任何地方,不妨將它刪除:)但問題是爲什麼它停止工作? – Alex

+0

可悲的是,仍然沒有解決這個問題 – Alex

+0

它停止工作,因爲你已經完全寫出請求之前試圖得到響應代碼。您沒有結果*,因爲*您沒有將它存儲在任何地方。對'getDoOutput()'的調用是毫無意義的。去掉它。 – EJP

0

已經找到了驚人的解決方案!今天路由器出現問題,所以上傳是很糟糕的。一旦從提供商切換到互聯網,它就像一個魅力:) GG!