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

查看:179
本文介绍了如何在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):

的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"
  />

在你的应用程序添加的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(该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天全站免登陆