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

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("");

}
});
}

}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值