本案例功能爲在輸入框中輸入網址並點擊按鈕,訪問HTML源代碼並顯示在TextView中。爲了避免服務器端編碼與客戶端不同,需要對返回的HTML代碼內容(標籤)進行判斷,採用與服務端對應的編碼進行解析。
實現步驟:
1. 定義函數String getHtmlFromInternet(String url),用於根據給定的url訪問網絡,抓取html代碼。函數的內容很簡單,仍然是定義HttpURLConnection對象,並配置各項參數,然後用connect進行連接。如果連接成功,調用String getStringFromInputStream(InputStream is)來將流轉換爲字符串。
2. 在getStringFromInputStream(InputStream is)方法中,主要做以下幾件事:(1)寫入緩存流;(2)在html中的內容中,抽取編碼信息,並做相應選擇判斷。(3)根據編碼信息做對應編碼種類的字符轉換,得到String類型的輸出字符html並返回。
3. 用戶點擊按鈕響應getHtml()方法。在這個方法中開啓一個子線程,接收返回到的html字符,如果不爲空,那麼將通過handler向主線程發送成功消息並傳遞html字符串。主線程將字符串顯示在UI中。
MainActivity.class
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
protected static final int SUCCESS = 0;
protected static final int ERROR = 1;
private static final String TAG = "MainActivity";
private EditText etUrl;
private TextView tvHtml;
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case SUCCESS:
tvHtml.setText((CharSequence) msg.obj);
break;
case ERROR:
Toast.makeText(MainActivity.this, "訪問失敗", 0).show();
break;
default:
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etUrl = (EditText) findViewById(R.id.et_url);
tvHtml = (TextView) findViewById(R.id.tv_html);
}
/**按鈕點擊,調用該方法。
*
* @param v
*/
public void getHtml(View v) {
final String url = etUrl.getText().toString();
new Thread(new Runnable() {
@Override
public void run() {
String html = getHtmlFromInternet(url);
if(!TextUtils.isEmpty(html)) {
Message msg = new Message();
msg.what = SUCCESS;
msg.obj = html;
handler.sendMessage(msg);
} else {
Message msg = new Message();
msg.what = ERROR;
handler.sendMessage(msg);
}
}
}).start();
}
/**
* 根據給定的url訪問網絡,抓取html代碼
* @param url
* @return
*/
protected String getHtmlFromInternet(String url) {
try {
URL mURL = new URL(url);
HttpURLConnection conn = (HttpURLConnection) mURL.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(10000);
conn.setReadTimeout(5000);
int responseCode = conn.getResponseCode();
if (responseCode == 200) {
InputStream is = conn.getInputStream();
String html = getStringFromInputStream(is);
return html;
} else {
Log.i(TAG, "訪問失敗"+responseCode);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 根據流返回一個字符串信息
* @param is
* @return
* @throws IOException
*/
private String getStringFromInputStream(InputStream is) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream(); //定義緩存流
byte[] buffer = new byte[1024]; //定義一個字節數組
int len = -1;
while((len = is.read(buffer))!= -1) { //如果沒有結束,執行寫入操作
baos.write(buffer, 0, len);
}
is.close();
String html = baos.toString(); //把流中的數據轉換成字符串
String charset = "utf-8";
if(html.contains("gbk") || html.contains("gb2312") ||
html.contains("GBK") || html.contains("GB2312")) { //如果包含gbk編碼,就採用gbk編碼對字符串編碼
charset = "gbk";
}
html = new String(baos.toByteArray(), charset); //按charset代表的編碼種類進行編碼,得到String類型的html
baos.close();
return html;
}
}