Android网络——Http通信

来源:互联网 发布:广告投放算法好吃 编辑:程序博客网 时间:2024/04/19 16:16


public class shape extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.shape);
final Handler hand = new Handler(){
public void handleMessage(android.os.Message msg) {
((ImageView) findViewById(R.id.iv)).setImageBitmap((Bitmap) msg.obj);
};
};
findViewById(R.id.tv).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
new Thread() {
public void run() {
try {
URL myFileURL = new URL("http://192.168.1.45:8080/jj/beauty.jpg");
    //获得连接
    HttpURLConnection conn=(HttpURLConnection)myFileURL.openConnection();
    //设置超时时间为6000毫秒,conn.setConnectionTiem(0);表示没有时间限制
    conn.setConnectTimeout(6000);
    //连接设置获得数据流
    conn.setDoInput(true);
    //不使用缓存
    conn.setUseCaches(false);
    //这句可有可无,没有影响
    //conn.connect();
    //得到数据流
    InputStream is = conn.getInputStream();
    //解析得到图片
    Message msg = new Message();
    msg.obj = BitmapFactory.decodeStream(is);
    //关闭数据流
    is.close();
hand.sendMessage(msg);
} catch (Exception e) {
}
};
}.start();
}
});
}

}


别忘了了添加权限:

<uses-permission android:name="android.permission.INTERNET" />


0 0