android http通信——HttpURLConntection
16lz
2021-01-23
Java代码
String urlpath="http://i2.sinaimg.cn/dy/dsgb/20083.jpg"; try {URL url=new URL(urlpath);HttpURLConnection con = (HttpURLConnection) url.openConnection();con.setConnectTimeout(6000);con.setRequestMethod("GET");if(con.getResponseCode()==200){byte[] imagebytes = readStreamtoBytes(con.getInputStream());File file =new File("pic.jpg");FileOutputStream fos =new FileOutputStream(file);fos.write(imagebytes);fos.close();}
Java代码
public static byte[] readStreamtoBytes(InputStream instream) throws IOException{
ByteArrayOutputStream outstream =new ByteArrayOutputStream();
int len=-1;
byte[] b = new byte[1024];
while((len = instream.read(b)) != -1){
outstream.write(b, 0, len);
}
outstream.flush();
outstream.close();
instream.close();
return outstream.toByteArray();
}
更多相关文章
- 在Eclipse 中关联android sdk 源代码
- 操作内存卡的常用代码
- android 根据SD卡中图片路径读取并显示SD中的图片——源代码
- android代码混淆及打包相关
- android 中生成XML文件的代码
- [置顶] [Android自定义控件]Android中如何用代码写出优美的Button
- recovery代码流程
- Android-开发常用代码汇总