Android學習(47) -- Html源文件查看器


發送GET請求

URL url = new URL(path);
//獲取連接對象
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//設置連接屬性
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
//建立連接,獲取響應嗎
if(conn.getResponseCode() == 200){

}

獲取服務器返回的流,從流中把html源碼讀取出來

由於構建字符串String,可以通過new String(byte[] )來構建,而ByteArrayOutputStream 可以調用.toByteArray(),能夠將流直接轉換爲字節數組

byte[] b = new byte[1024];
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while((len = is.read(b)) != -1){
    //把讀到的字節先寫入字節數組輸出流中存起來
    bos.write(b, 0, len);
}
//把字節數組輸出流中的內容轉換成字符串
//默認使用utf-8
text = new String(bos.toByteArray());

亂碼的處理

亂碼的出現是因爲服務器和客戶端碼錶不一致導致
//手動指定碼錶
text = new String(bos.toByteArray(), "utf-8");

核心代碼

public class MainActivity extends Activity {

	Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			TextView tv = (TextView) findViewById(R.id.tv);
			tv.setText((String)msg.obj);
		}
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}

	public void click(View v){
		Thread t = new Thread(){
			@Override
			public void run() {
				String path = "http://192.168.1.103:8080/baidu.html";
				try {
					URL url = new URL(path);
					//獲取連接對象,此時還未建立連接
					HttpURLConnection conn = (HttpURLConnection) url.openConnection();
					conn.setRequestMethod("GET");
					conn.setConnectTimeout(5000);
					conn.setReadTimeout(5000);
					//先建立連接,然後獲取響應碼
					if(conn.getResponseCode() == 200){
						//拿到服務器返回的輸入流,流裏的數據就是html的源文件
						InputStream is = conn.getInputStream();
						//從流裏把文本數據取出來
						String text = Utils.getTextFromStream(is);
						
						//發送消息,讓主線程刷新ui,顯示源文件
						Message msg = handler.obtainMessage();
						msg.obj = text;
						handler.sendMessage(msg);
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		};
		t.start();
		
	}

}

從流中獲取到字符串
public class Utils {

	public static String getTextFromStream(InputStream is){
		
		byte[] b = new byte[1024];
		int len = 0;
		//創建字節數組輸出流,讀取輸入流的文本數據時,同步把數據寫入數組輸出流
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		try {
			while((len = is.read(b)) != -1){
				bos.write(b, 0, len);
			}
			//把字節數組輸出流裏的數據轉換成字節數組
			String text = new String(bos.toByteArray());
			return text;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
}



發佈了101 篇原創文章 · 獲贊 7 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章