在Android开发中,通常经过网络进行访问服务器端的信息(存储和检索网络中的数据),如API接口,WebService,网络图片等。今天主要讲解Http访问的经常使用方法,仅供学习分享使用。html
以下图所示:android
获取数据类web
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访问的相关知识还有不少,本文知识简单粗略的讲解,但愿抛砖引玉,共同窗习。ide