Reputation: 249
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;
}
before conn.setRequestMethod("GET")
was excuted,thorws the exception Connection already established. who can give me a solution
Upvotes: 1
Views: 6160
Reputation: 500
This is happening because you're connecting before setting the request method
A suggest you try this:
conn.setRequestMethod("GET");
conn.connect);
conn.setConnectTimeout(5000);
is = conn.getInputStream();
byte[] imgbytes = StreamTool.getBytes(is);
Upvotes: 0
Reputation: 1
Experienced same, find out the IDE is watching a field of the connection which I have added to debug, then cause the connection get established before other code run like set properties.
So if you want to get some "properties" before connection is ready during debug, you will get this error
Upvotes: 0
Reputation: 4076
I know it is completely nonsense. But it happens for me in debug mode when I put break point on this line.
con.setRequestMethod()
As soon as I removed the break point, the error has gone!
Upvotes: 7
Reputation: 4636
When you create an instance of HttpURLConnection it defaults to the request method GET so there is no need to call setRequestMethod in this instance.
This link contains some fantastic detail about HTTP connections and how to use them.
Upvotes: 0
Reputation: 585
Thats because the function setRequestMethod()
has to be called before the connection is made.
Check this link
So better call it before openConnection(). Or dont call it at all.
Upvotes: -3