韩少的勾心妻,焰色沦落妃,ca4229
在android开发中,一般通过网络进行访问服务器端的信息(存储和检索网络中的数据),如api接口,webservice,网络图片等。今天主要讲解http访问的常用方法,仅供学习分享使用。
如下图所示:
获取数据类
1 /** 2 * created by hex on 2019/4/6. 3 */ 4 public class getdata { 5 // 定义一个获取网络图片数据的方法: 6 public static byte[] getimage(string path) throws exception { 7 url url = new url(path); 8 httpurlconnection conn = (httpurlconnection) url.openconnection(); 9 // 设置连接超时为5秒 10 conn.setconnecttimeout(5000); 11 // 设置请求类型为get类型 12 conn.setrequestmethod("get"); 13 // 判断请求url是否成功 14 if (conn.getresponsecode() != 200) { 15 throw new runtimeexception("请求url失败"); 16 } 17 inputstream instream = conn.getinputstream(); 18 byte[] bt = streamtool.read(instream); 19 instream.close(); 20 return bt; 21 } 22 23 // 获取网页的html源代码 24 public static string gethtml(string path) throws exception { 25 url url = new url(path); 26 httpurlconnection conn = (httpurlconnection) url.openconnection(); 27 conn.setconnecttimeout(5000); 28 conn.setrequestmethod("get"); 29 if (conn.getresponsecode() == 200) { 30 inputstream in = conn.getinputstream(); 31 byte[] data = streamtool.read(in); 32 string html = new string(data, "utf-8"); 33 return html; 34 } 35 return null; 36 } 37 }
inputstream转换为byte[]功能
1 /** 2 * created by administrator on 2019/4/6. 3 */ 4 public class streamtool { 5 //从流中读取数据 6 public static byte[] read(inputstream instream) throws exception { 7 bytearrayoutputstream outstream = new bytearrayoutputstream(); 8 byte[] buffer = new byte[1024]; 9 int len = 0; 10 while ((len = instream.read(buffer)) != -1) { 11 outstream.write(buffer, 0, len); 12 } 13 instream.close(); 14 return outstream.tobytearray(); 15 } 16 }
刷新界面赋值
1 // 用于刷新界面 2 private handler handler = new handler() { 3 public void handlemessage(android.os.message msg) { 4 switch (msg.what) { 5 case 0x001: 6 hideallwidget(); 7 imgpic.setvisibility(view.visible); 8 imgpic.setimagebitmap(bitmap); 9 toast.maketext(mainactivity.this, "图片加载完毕", toast.length_short).show(); 10 break; 11 case 0x002: 12 hideallwidget(); 13 scroll.setvisibility(view.visible); 14 txtshow.settext(detail); 15 toast.maketext(mainactivity.this, "html代码加载完毕", toast.length_short).show(); 16 break; 17 case 0x003: 18 hideallwidget(); 19 webview.setvisibility(view.visible); 20 webview.loaddatawithbaseurl("", detail, "text/html", "utf-8", ""); 21 toast.maketext(mainactivity.this, "网页加载完毕", toast.length_short).show(); 22 break; 23 default: 24 break; 25 } 26 } 27 28 ; 29 };
如果要访问网络,还需要有相应的权限
1 <uses-permission android:name="android.permission.internet" />
关于http访问的相关知识还有很多,本文知识简单粗略的讲解,希望抛砖引玉,共同学习。
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
Android apk 项目一键打包并上传到蒲公英的实现方法
Android 自定义LineLayout实现满屏任意拖动功能的示例代码
android 限制某个操作每天只能操作指定的次数(示例代码详解)
Android 集成 google 登录并获取性别等隐私信息的实现代码
网友评论