您的位置:首页 > 理论基础 > 计算机网络

完成一个应用,用户可以根据自己输入的地址下载网络上的图片和网页信息

2012-12-26 20:42 1151 查看
import java.io.ByteArrayOutputStream;

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.util.Log;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.EditText;

import android.widget.ImageView;

import android.widget.TextView;

import android.widget.Toast;

public class MainActivity extends Activity {

EditText edit;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

edit = (EditText) findViewById(R.id.editText1);

Button huoqu = (Button) findViewById(R.id.button1);

Button clear = (Button) findViewById(R.id.button2);

huoqu.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View v) {

String path = edit.getText().toString();

try {

URL url = new URL(path);

HttpURLConnection connection = (HttpURLConnection) url

.openConnection();

connection.setConnectTimeout(5 * 1000);

connection.setRequestMethod("GET");

if (connection.getResponseCode() != 200) {

throw new RuntimeException("请求url失败");

}

InputStream input = connection.getInputStream();

ByteArrayOutputStream output = new ByteArrayOutputStream();

byte[] bt = new byte[1024];

int length = -1;

while ((length = input.read(bt)) != -1) {

output.write(bt, 0, length);

}

byte data[] = output.toByteArray();

if (path.endsWith(".jpg")||path.endsWith(".JPG")) {

ImageView iv = (ImageView) findViewById(R.id.imageView1);

Bitmap bit = BitmapFactory.decodeByteArray(data, 0,

data.length);

iv.setImageBitmap(bit);

} else if (path.endsWith(".com")||path.endsWith(".COM")) {

TextView tv = (TextView) findViewById(R.id.textView2);

tv.setText(new String(data, "UTF-8"));

} else {

Toast.makeText(getBaseContext(), "只能获取图片或图片!",

Toast.LENGTH_LONG).show();

}

;

} catch (Exception e) {

e.printStackTrace();

Log.i("TAG", e.toString());

Toast.makeText(getBaseContext(), "出错了,找不到数据", 1).show();

}

}

});

clear.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View v) {

edit.setText("");

}

});

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐