Created
July 12, 2017 11:53
-
-
Save 5ZSQ/73f9c9efd8e9b17a24ee4a7b373279f2 to your computer and use it in GitHub Desktop.
Android - 网络请求坑-setDoOutput
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 从Url中获取Bitmap | |
* | |
* @param url | |
* @return | |
*/ | |
private Bitmap getBitmapFormUrl(String url) { | |
Bitmap bitmap = null; | |
HttpURLConnection con = null; | |
try { | |
URL mImageUrl = new URL(url); | |
con = (HttpURLConnection) mImageUrl.openConnection(); | |
con.setConnectTimeout(10 * 1000); | |
con.setReadTimeout(10 * 1000); | |
con.setDoInput(true); | |
// con.setDoOutput(true); //注意设置为true仅为post时,GET 方式需要忽略,否则405错误 | |
con.setInstanceFollowRedirects(true); | |
con.setRequestMethod("GET"); | |
Logger.i("url:"+url+", getResponseCode:"+con.getResponseCode()); | |
if (con.getResponseCode() >= HttpURLConnection.HTTP_OK | |
&& con.getResponseCode()< 300){ //OK | |
bitmap = BitmapFactory.decodeStream(con.getInputStream()); | |
}else{ | |
Logger.i("url:"+url+", getResponseCode:"+con.getResponseCode() | |
+",content:"+ ConvertToString(con.getErrorStream())); | |
} | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} finally { | |
if (con != null) { | |
con.disconnect(); | |
} | |
} | |
return bitmap; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment