android java.net.ProtocolException:已建立连接

时间:2013-11-04 11:01:22

标签: java android

public static Bitmap getImage(String address) throws Exception {

    Bitmap imgmap = null;
    InputStream is = null;

    URL url = new URL(address);

    HttpURLConnection  conn = (HttpURLConnection)url.openConnection();
    try {
        conn.setRequestMethod("GET"); >>> here was been excuted,but go to finally block
        conn.setConnectTimeout(5000); 
        is = conn.getInputStream();
        byte[] imgbytes = StreamTool.getBytes(is);
        imgmap = BitmapFactory.decodeByteArray(imgbytes, 0, imgbytes.length);

    } finally {
        if (is != null) {
            is.close();
        }
        if (conn != null) {
            conn.disconnect();
        }
    }

    return imgmap;
}

conn.setRequestMethod("GET")执行之前,抛出已建立的异常连接。谁可以给我一个解决方案

4 个答案:

答案 0 :(得分:7)

我知道这完全是胡说八道。但是当我在此行上设置断点时,它会在调试模式下发生。

  

con.setRequestMethod()

一旦我删除了断点,错误就消失了!

答案 1 :(得分:0)

当您创建HttpURLConnection的实例时,它默认为请求方法 GET ,因此在此实例中无需调用setRequestMethod。

This link包含一些有关HTTP连接以及如何使用它们的精彩细节。

答案 2 :(得分:0)

发生这种情况是因为您在设置请求方法

之前进行了连接

建议你试试这个:

conn.setRequestMethod("GET");
conn.connect);
conn.setConnectTimeout(5000); 
is = conn.getInputStream();
byte[] imgbytes = StreamTool.getBytes(is);

答案 3 :(得分:-3)

这是因为在建立连接之前必须调用函数setRequestMethod()。 检查此链接

http://developer.android.com/reference/java/net/HttpURLConnection.html#setRequestMethod(java.lang.String)

所以最好在openConnection()之前调用它。或者根本不打电话。