xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:orientation="vertical"
tools:context="com.jiutouxiang.help.WebSourceViewerActivity">
<EditText
android:id="@+id/et_url"
android:hint="请输入网址"
android:textColor="#333333"
android:textColorHint="#888888"
android:text="https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/bt_go"
android:text="查看"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/iv_picture"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</ScrollView>
</LinearLayout>
java:
package com.jiutouxiang.help;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import com.jiutouxiang.R;
import com.jiutouxiang.base.MyActivity;
import com.jiutouxiang.toolkits.ForLog;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class PictureViewerActivity extends MyActivity {
private ImageView iv_picture;
private Button bt_go;
private Activity activity;
private EditText et_url;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_picture_viewer);
iv_picture=(ImageView)findViewById(R.id.iv_picture);
activity=this;
et_url=(EditText)activity.findViewById(R.id.et_url);
bt_go=(Button)activity.findViewById(R.id.bt_go);
bt_go.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new Runnable() {
@Override
public void run() {
//获取路径
String path=et_url.getText().toString().trim();
getPictureByPath(path);
}
}).start();
}
});
}
private void getPictureByPath(String path) {
try {
URL url=new URL(path);
//拿到HttpURLConnection对象,用于接受和发送数据
HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
//设置请求方式
// httpURLConnection.setRequestMethod("GET");
//设置请求超时时间:5s
// httpURLConnection.setConnectTimeout(5000);
//获取服务器返回响应吗
int code=httpURLConnection.getResponseCode();
if (code==200){
//说明请求成功
final InputStream in=httpURLConnection.getInputStream();
final Bitmap bitmap=BitmapFactory.decodeStream(in);
runOnUiThread(new Runnable() {
@Override
public void run() {
iv_picture.setImageBitmap(bitmap);
}
});
} else{
ForLog.showError("返回代码错误:"+code+"---"+path);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}