运行效果图:
建立项目:D3PhotoLook;
首先加入网络权限:如图
MainActivity.java的全部代码:
package cn.example.d3_photolook;
import java.io.InputStream;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
public class MainActivity extends Activity
{
private EditText et_path;
private ImageView iv;
// 创建handler 对象
private Handler handler = new Handler()
{
public void handleMessage(android.os.Message msg)
{
Bitmap bitmap = (Bitmap) msg.obj;
iv.setImageBitmap(bitmap);
};
};
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_path = (EditText) findViewById(R.id.et_path);
iv = (ImageView) findViewById(R.id.iv);
}
public void click(View v)
{
new Thread()
{
public void run()
{
try
{
// 访问路径
String path = et_path.getText().toString().trim();
// 创建url对象
URL url = new URL(path);
// 获取 HttpsURLConnection
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
// 设置请求的方式
conn.setRequestMethod("GET");
// 设置超时时间
conn.setConnectTimeout(5000);
// 获取服务器返回的状态码
int code = conn.getResponseCode();
if (code == 200)
{
// 获取图片的数据
InputStream in = conn.getInputStream();
// 通过位图工厂获取bitmap
Bitmap bitmap = BitmapFactory.decodeStream(in);
// 把bitmap显示到iv上
Message msg = Message.obtain();
msg.obj = bitmap;
handler.sendMessage(msg);
}
} catch (Exception e)
{
e.printStackTrace();
}
};
}.start();
}
}
activity_main.xml的代码:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="cn.example.d3_photolook.MainActivity" >
<EditText
android:id="@+id/et_path"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="https://www.baidu.com/img/bd_logo1.png"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="click"
android:text="查看" />
<ImageView
android:id="@+id/iv"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>