今天学习了安卓开发中有关网络通信相关的东西。
根据教学视频,我按照步骤写了一个“网页源码查看器”。通过写这个东西,我学会了使用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.的工具类,也是要自己去写的,通过写这个类,学会了java中IO流的部分应用。
下面代码中的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);//显示图片