主要用到了ByteArrayOutputStream类。该类无需指定输出流的路径,而是将数据直接输出到内存缓冲区。
使用toByteArray方法获取内存缓冲区数据。
1 package com.example.day10_03htmlsourceViewer; 2 3 import java.io.ByteArrayOutputStream; 4 import java.io.InputStream; 5 import java.net.HttpURLConnection; 6 import java.net.URL; 7 import android.app.Activity; 8 import android.os.Bundle; 9 import android.os.Handler; 10 import android.os.Message; 11 import android.view.View; 12 import android.widget.TextView; 13 import android.widget.Toast; 14 15 public class MainActivity extends Activity { 16 @Override 17 protected void onCreate(Bundle savedInstanceState) { 18 super.onCreate(savedInstanceState); 19 setContentView(R.layout.activity_main); 20 } 21 22 final static int MSG_DOWNLOAD_OK =1; 23 final static int MSG_DOWNLOAD_ERROR =2; 24 25 Handler handler = new Handler(){ 26 @Override 27 public void handleMessage(Message msg) { 28 super.handleMessage(msg); 29 30 switch (msg.what) { 31 case MSG_DOWNLOAD_OK: 32 TextView tv_html= (TextView) findViewById(R.id.tv_html); 33 tv_html.setText((String)msg.obj); 34 break; 35 case MSG_DOWNLOAD_ERROR: 36 Toast.makeText(MainActivity.this, "下载源码失败", 1).show(); 37 break; 38 default: 39 break; 40 } 41 } 42 }; 43 public void gethtml(View v){ 44 Thread thread = new Thread(){ 45 public void run() { 46 String path = "http://192.168.3.30:8080/index2.html"; 47 try { 48 URL url = new URL(path); 49 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 50 51 conn.setConnectTimeout(5000); 52 conn.setReadTimeout(5000); 53 conn.setRequestMethod("GET"); 54 conn.connect(); 55 56 if(conn.getResponseCode()==200) 57 { 58 InputStream is = conn.getInputStream(); 59 60 ByteArrayOutputStream baos = new ByteArrayOutputStream(); 61 byte[] b = new byte[1024]; 62 int len = 0; 63 while((len=is.read(b))!=-1) 64 { 65 baos.write(b, 0, len); 66 } 67 is.close(); 68 baos.close(); 69 String htmlsource = new String(baos.toByteArray(),"GBK") ; 70 Message msg= handler.obtainMessage(); 71 msg.what=MSG_DOWNLOAD_OK; 72 msg.obj=htmlsource; 73 handler.sendMessage(msg); 74 } 75 else { 76 Message msg= handler.obtainMessage(); 77 msg.what=MSG_DOWNLOAD_ERROR; 78 handler.sendMessage(msg); 79 } 80 } catch ( Exception e) { 81 e.printStackTrace(); 82 } 83 } 84 ; 85 }; 86 thread.start(); 87 } 88 }
activity_main.xml和AndroidManifest.xml与010_02带缓存的图片查看器相同。
效果图:
时间: 2024-10-08 07:35:48