Mac*_*cky 15

我建议阅读android-api提供的教程.

下面是一些使用DefaultHttpClient的随机示例,通过examples-folder中的简单文本搜索找到.

编辑:样本源不是为了显示某些东西.它只是请求了url的内容并将其存储为字符串.下面是一个显示它加载内容的示例(只要它是字符串数据,如html-,css-或javascript-文件):

main.xml中

  <?xml version="1.0" encoding="utf-8"?>
  <TextView xmlns:android="http://schemas.android.com/apk/res/android"
     android:id="@+id/textview"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent"
  />
Run Code Online (Sandbox Code Playgroud)

在你的应用程序的onCreate添加:

  // Create client and set our specific user-agent string
  HttpClient client = new DefaultHttpClient();
  HttpGet request = new HttpGet("http://stackoverflow.com/opensearch.xml");
  request.setHeader("User-Agent", "set your desired User-Agent");

  try {
      HttpResponse response = client.execute(request);

      // Check if server response is valid
      StatusLine status = response.getStatusLine();
      if (status.getStatusCode() != 200) {
          throw new IOException("Invalid response from server: " + status.toString());
      }

      // Pull content stream from response
      HttpEntity entity = response.getEntity();
      InputStream inputStream = entity.getContent();

      ByteArrayOutputStream content = new ByteArrayOutputStream();

      // Read response into a buffered stream
      int readBytes = 0;
      byte[] sBuffer = new byte[512];
      while ((readBytes = inputStream.read(sBuffer)) != -1) {
          content.write(sBuffer, 0, readBytes);
      }

      // Return result from buffered stream
      String dataAsString = new String(content.toByteArray());

      TextView tv;
      tv = (TextView) findViewById(R.id.textview);
      tv.setText(dataAsString);

  } catch (IOException e) {
     Log.d("error", e.getLocalizedMessage());
  }
Run Code Online (Sandbox Code Playgroud)

此示例现在加载给定URL的内容(示例中的stackoverflow的OpenSearchDescription),并将接收的数据写入TextView.