2015-07-10 98 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!