package com.jiangge.imageviewer;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity {
ImageView imageView;
EditText editPath;
Handler hadHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.image_view);
editPath = (EditText) findViewById(R.id.it_path);
hadHandler = new Handler();
}
public void click(View view){
final String path = editPath.getText().toString().trim();
if (TextUtils.isEmpty(path)) {
Toast.makeText(this,"路径不能为空", Toast.LENGTH_LONG).show();
return;
}
new Thread(){
public void run(){
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
// conn.setReadTimeout();
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0");
int code = conn.getResponseCode();
System.out.println("===>>>" + code);
if (code == 200) {
InputStream is = conn.getInputStream();
final Bitmap bitmap = BitmapFactory.decodeStream(is);
hadHandler.post(new Runnable() {
@Override
public void run() {
imageView.setImageBitmap(bitmap);
}
});
}else {
Toast.makeText(MainActivity.this,"获取图片失败", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(MainActivity.this,"获取图片失败", Toast.LENGTH_LONG).show();
}
}
}.start();
}
}
布局文件:
<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=".MainActivity" >
<ImageView
android:id="@+id/image_view"
android:layout_weight="1000"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<EditText
android:id="@+id/it_path"
android:singleLine="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="http://g.hiphotos.baidu.com/image/w%3D2048/sign=fa4ce6add31b0ef46ce89f5ee9fc50da/f636afc379310a55ed977077b64543a983261085.jpg"
android:hint="图片路径" >
</EditText>
<Button
android:id="@+id/btn"
android:onClick="click"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="发送请求" >
</Button>
</LinearLayout>