useragent的使用
可以欺骗服务器,用手机可以获取电脑的类型。
conn.setRequestProperty("User-Agent","....");
网络请求图片
public class MainActivity extends Activity {
protected static final int SUCCESS = 1;
protected static final int ERROR = 2;
private EditText et_path;
private ImageView iv;
private Button bt_00;
//1.得到消息处理器
private Handler handler = new Handler(){
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case SUCCESS:
Bitmap bitmap = (Bitmap) msg.obj;
iv.setImageBitmap(bitmap);
break;
case ERROR:
Toast.makeText(MainActivity.this, "获取图片失败", 0).show();
break;
}
};
};
@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);
bt_00 = (Button) findViewById(R.id.bt_00);
bt_00.setOnClickListener(viewImage);
}
/**
* 点击查看图片
*
* @param view
*/
OnClickListener viewImage = new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
final String path = et_path.getText().toString().trim();
if (TextUtils.isEmpty(path)) {
Toast.makeText(MainActivity.this, "对不起,图片路径不能为空", 0).show();
return;
}
new Thread(){
public void run() {
//开启新的子线程 去请求网络 获取数据
// 显示这个互联网上的图片
try {
// 1.得到图片的url路径
URL url = new URL(path);
// 2.通过路径打开一个http的连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();// http
conn.setRequestMethod("GET");//设置请求参数为get, 默认的请求方式就是get
conn.setConnectTimeout(5000);//设置请求服务器的超时时间.
// 3.得到服务器的返回信息
String type = conn.getContentType();
int length = conn.getContentLength();
System.out.println("服务器资源的长度:"+length);
System.out.println("服务器返回的数据类型:" + type);
int code = conn.getResponseCode(); // 200 OK 404 资源没找到 503服务器内部错误
if (code == 200) {
InputStream is = conn.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(is);
//iv.setImageBitmap(bitmap);
//不能直接更新ui,通过发消息让handler去更新ui
Message msg = Message.obtain();//节约了内存
msg.what = SUCCESS;
msg.obj = bitmap;
handler.sendMessage(msg);
is.close();
}
} catch (Exception e) {
e.printStackTrace();
Message msg = Message.obtain();
msg.what = ERROR;
handler.sendMessage(msg);
}
};
}.start();
}
};
}