2.用户可以根据自己输入的地址下载网页信息
第一步:先写布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="显示下载的网页" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="下载html" />
<TextView
android:id="@+id/textView2"
android:layout_width="81dp"
android:layout_height="wrap_content"
android:minLines="5"
android:text="TextView" />
</LinearLayout>
第二步再写activity
package com.hbsi.csdn.picture;
import com.hsbi.csdn.service.ImageService;
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.TextView;
import android.widget.Toast;
public class showhtmlActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.showhtml);
Button btn2 = (Button) findViewById(R.id.button2);
final TextView tv=(TextView) findViewById(R.id.textView2);
btn2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String path="http://www.sohu.com";
try {
byte[] data = ImageService.getImage(path);
tv.setText(new String(data,"GBK"));
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), "出错了,找不到图片",1).show();
Log.e("ERR",e.toString());;
}
}
});
}
}
第三步:
单独写一个imageservice类
package com.hsbi.csdn.service;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class ImageService {
public static byte[] getImage(String path) throws Exception{
URL url=new URL(path);//得到代表路径的url;
HttpURLConnection conn=(HttpURLConnection) url.openConnection();
conn.setConnectTimeout(20*1000);
conn.setRequestMethod("GET");
if (conn.getResponseCode() != 200) throw new RuntimeException("请求url失败");
InputStream in=conn.getInputStream();
ByteArrayOutputStream outStream=new ByteArrayOutputStream();
byte[] buffer=new byte[1024];
int len=-1;
while((len=in.read(buffer))!=-1){
outStream.write(buffer,0,len);
}
byte[] data=outStream.toByteArray();//图片的二进制数组
return data;
}
}
第四步:在清单文件中注册activity
<activity android:name=".showhtmlActivity"></activity>