|
當我想抓取網頁某個位置的的內容的時候
需要先讀取出該網頁內容
google找了許久
終於測試成功code
當然在貼上代碼之前
請先確認你的ANDROID XML網路連接程式代碼有加入
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- new HttpTask().execute("http://www.google.com");
- }
- public String getWebPage(String adresse) {
- HttpClient httpClient = new DefaultHttpClient();
- HttpGet httpGet = new HttpGet();
- InputStream inputStream = null;
- String response = null;
- try {
- URI uri = new URI(adresse);
- httpGet.setURI(uri);
- HttpResponse httpResponse = httpClient.execute(httpGet);
- int statutCode = httpResponse.getStatusLine().getStatusCode();
- int length = (int) httpResponse.getEntity().getContentLength();
- Log.d("main", "HTTP GET: " + adresse);
- Log.d("main", "HTTP StatutCode: " + statutCode);
- Log.d("main", "HTTP Lenght: " + length + " bytes");
- inputStream = httpResponse.getEntity().getContent();
- Reader reader = new InputStreamReader(inputStream, "UTF-8");
- int inChar;
- StringBuffer stringBuffer = new StringBuffer();
- while ((inChar = reader.read()) != -1) {
- stringBuffer.append((char) inChar);
- }
- response = stringBuffer.toString();
- } catch (ClientProtocolException e) {
- Log.d("main", "HttpActivity.getPage() ClientProtocolException error", e);
- } catch (IOException e) {
- Log.d("main", "HttpActivity.getPage() IOException error", e);
- } catch (URISyntaxException e) {
- Log.d("main", "HttpActivity.getPage() URISyntaxException error", e);
- } finally {
- try {
- if (inputStream != null)
- inputStream.close();
- } catch (IOException e) {
- Log.e(LOG_THREAD_ACTIVITY, "HttpActivity.getPage() IOException error lors de la fermeture des flux", e);
- }
- }
- return response;
- }
- private class HttpTask extends AsyncTask<String, Integer, String> {
- @Override
- protected String doInBackground(String... urls) {
- // TODO Auto-generated method stub
- String response = getWebPage(urls[0]);
- return response;
- }
- @Override
- protected void onPostExecute(String response) {
- Log.d("main", "HTTP RESPONSE" + response);
- //tv1.setText(response);
- }
- @Override
- protected void onPreExecute() {
- // TODO Auto-generated method stub
- super.onPreExecute();
- }
- @Override
- protected void onProgressUpdate(Integer... values) {
- // TODO Auto-generated method stub
- super.onProgressUpdate(values);
- }
- }
複製代碼 參考文章http://stackoverflow.com/questio ... site-in-android-app
|
|