【Android开发】网络通信之网页源码查看器

今天学习了安卓开发中有关网络通信相关的东西。

根据教学视频,我按照步骤写了一个“网页源码查看器”。通过写这个东西,我学会了使用URL和 HttpURLConnection取得与网站的链接

 

部分链接代码:

/*
     * 获取网页html源代码:
     * path 网页路径
     * */
public static String getHtml(String path) throws Exception{
//将path包装成一个URL对象
    URL url=new URL(path);
    //取得链接对象(基于HTTP协议链接对象)
    HttpURLConnection conn=(HttpURLConnection) url.openConnection();
    //设置超时时间
    conn.setConnectTimeout(5000);
    //设置请求方式
    conn.setRequestMethod("GET");
    //判断请求是否成功(看一下getResponseCode)
    if(conn.getResponseCode()==200){
    	InputStream instream=conn.getInputStream();
    	//流的工具类,专门从流中读取数据(返回的是二进制数据)
    	byte[] data= streamTool.read(instream);
    	String html= new String(data,"UTF-8");
    	return html;
    }
return null;
}

 

上面的代码中有一个streamTool.的工具类,也是要自己去写的,通过写这个类,学会了javaIO流的部分应用。

 

下面代码中的instream是上面传进去的输入流对象

部分代码:

/*
     * 读取流中的数据
     * */
public static byte[] read(InputStream instream) throws Exception{
ByteArrayOutputStream outStream=new ByteArrayOutputStream();
//定义一个字节数组
byte[] buffer=new byte[1024];
//读满数组,就会返回(返回的是int型,代表读取的数组长度)
//当返回值为-1时说明已经读完
int len=0;
while((len = instream.read(buffer)) !=-1){
//buffer有多少数据就读多少
outStream.write(buffer, 0, len);
}
instream.close();
return outStream.toByteArray();
}


在主界面得到html信息并显示

private EditText pathText;
    private TextView codeView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
pathText=(EditText) findViewById(R.id.pagepath);
codeView=(TextView) findViewById(R.id.codeview);
Button button=(Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String path=pathText.getText().toString();
String html;
try {
html = PageSevice.getHtml(path);
codeView.setText(html);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), R.string.error, 1).show();
}
}
});
 
}

效果图:



 转载请注明原址:http://blog.csdn.net/acmman


读取图片也不难,显示界面稍加改造即可(当然相应的类(ImageSevice)也要写)

Image View imageView =(Image View) findviewbyId(R.id.imageview);

String path=pathText.getText().toString();
byte[] data=ImageSevice.getImage(path);
Bitmap bitmap=BitmapFactory.decodeByteArray(data,0,data.length);
imageView.setImageBitmap(bitmap);//显示图片

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

光仔December

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值