1.继续昨天的代码验证
获取数据类:GetData.java:
/** * Created by Jay on 2015/9/7 0007. */ public class GetData { // 定义一个获取网络图片数据的方法: public static byte[] getImage(String path) throws Exception { URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 设置连接超时为5秒 conn.setConnectTimeout(5000); // 设置请求类型为Get类型 conn.setRequestMethod("GET"); // 判断请求Url是否成功 if (conn.getResponseCode() != 200) { throw new RuntimeException("请求url失败"); } InputStream inStream = conn.getInputStream(); byte[] bt = StreamTool.read(inStream); inStream.close(); return bt; } // 获取网页的html源代码 public static String getHtml(String path) throws Exception { URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5000); conn.setRequestMethod("GET"); if (conn.getResponseCode() == 200) { InputStream in = conn.getInputStream(); byte[] data = StreamTool.read(in); String html = new String(data, "UTF-8"); return html; } return null; } }
MainActivity.java:
public class MainActivity extends AppCompatActivity {
private TextView txtMenu, txtshow;
private ImageView imgPic;
private WebView webView;
private ScrollView scroll;
private Bitmap bitmap;
private String detail = "";
private boolean flag = false;
private final static String PIC_URL = "https://ww2.sinaimg.cn/large/7a8aed7bgw1evshgr5z3oj20hs0qo0vq.jpg";
private final static String HTML_URL = "https://www.baidu.com";
// 用于刷新界面
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case 0x001:
hideAllWidget();
imgPic.setVisibility(View.VISIBLE);
imgPic.setImageBitmap(bitmap);
Toast.makeText(MainActivity.this, "图片加载完毕", Toast.LENGTH_SHORT).show();
break;
case 0x002:
hideAllWidget();
scroll.setVisibility(View.VISIBLE);
txtshow.setText(detail);
Toast.makeText(MainActivity.this, "HTML代码加载完毕", Toast.LENGTH_SHORT).show();
break;
case 0x003:
hideAllWidget();
webView.setVisibility(View.VISIBLE);
webView.loadDataWithBaseURL("", detail, "text/html", "UTF-8", "");