Android开发网络编程,请求图片
上一篇文章我们使用了Java的API来请求到了网络数据,全是文本内容。
现在呢,咱们去请求图片内容,返回的结果可不是文本了。看看怎么整吧!
网络权限和配置
<uses-permission android:name="android.permission.INTERNET" />
网络配置:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config>
<domain includeSubdomains="true">sunofbeaches.com</domain>
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="true">www.sunofbeach.net</domain>
<domain includeSubdomains="true">imgs.sunofbeaches.com</domain>
</domain-config>
</domain-config>
</network-security-config>
允许这些域名明文访问,否则http会报错
请求图片内容
public void requestImage(View view) {
new Thread(new Runnable() {
@Override
public void run() {
loadImage();
}
}).start();
}
private void loadImage() {
try {
URL url = new URL("https://imgs.sunofbeaches.com/group1/M00/00/05/rBsADV2rEz-AIzSoAABi-6nfiqs456.png");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setConnectTimeout(10000);
httpURLConnection.connect();
InputStream is = httpURLConnection.getInputStream();
final Bitmap bitmap = BitmapFactory.decodeStream(is);
runOnUiThread(new Runnable() {
@Override
public void run() {
ImageView resultView = findViewById(R.id.image_result);
resultView.setImageBitmap(bitmap);
}
});
} catch(Exception e) {
e.printStackTrace();
}
}
处理结果显示图片
UI上就一个Button和一个ImageView
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="requestImage"
android:text="请求图片" />
<ImageView
android:id="@+id/image_result"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
测试结果
到这里图片就载出来了,但是有没对图片的采样率做处理,如果是大图片的话,可能会OOM哦,后面我们继续去解决大图片的加载问题。
这里面其实就是把图片流,通过一个BitmapFactory来对流进行编码,转成图片内容,显示到控件上。