Http请求 - 已经连接

时间:2015-07-10 09:36:41

标签: java android httpurlconnection

基本上我已经使用这些特定代码行很长一段时间了,从来没有遇到过问题。什么都没有被触及,但现在我正在接受

  

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();
        }

3 个答案:

答案 0 :(得分:0)

将此代码写入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(); } } 块,然后尝试

public class Master : IService
public class Settings : ISettings

答案 1 :(得分:0)

您需要在获取响应代码之前编写请求。

close()之前移动getResponseCode(),然后删除多余的flush()

NB为什么要调用getDoOutput()并忽略结果?

答案 2 :(得分:0)

已找到惊人的解决方案!今天路由器出现了问题,所以上传很糟糕。一旦从提供商切换到互联网,它就像一个魅力:) GG!