如何在 Android 中使用 DefaultHttpClient? [英] How to use DefaultHttpClient in Android?

查看:106
本文介绍了如何在 Android 中使用 DefaultHttpClient?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Android 中使用 DefaultHttpClient?

How to use DefaultHttpClient in Android?

推荐答案

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

I suggest reading the tutorials provided with android-api.

这是一些使用 DefaultHttpClient 的随机示例,通过在示例文件夹中的简单文本搜索找到.

Here is some random example which uses DefaultHttpClient, found by simple text-search in examples-folder.

示例源不打算显示某些内容.它只是请求 url 的内容并将其存储为字符串.这是一个显示它加载的内容的示例(只要它是字符串数据,如 html-、css- 或 javascript-文件):

The sample-source was not intended to show something. It just requested the content of the url and stored it as string. Here is an example which shows what it loaded (as long as it is string-data, like an html-, css- or javascript-file):

ma​​in.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"
  />

在您的应用的 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());
  }

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

This example now loads the content of the given url (the OpenSearchDescription for stackoverflow in the example) and writes the received data in an TextView.

这篇关于如何在 Android 中使用 DefaultHttpClient?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆