7

AndroidでDefaultHttpClientを使用するには?

4

3 に答える 3

15

android-api で提供されているチュートリアルを読むことをお勧めします。

これは、examples-folder で単純なテキスト検索によって見つかった、DefaultHttpClient を使用するランダムな例です。

編集: サンプル ソースは、何かを表示するためのものではありませんでした。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"
  />

アプリの 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 に書き込みます。

于 2011-03-23T19:59:25.030 に答える
3

一般的なコード例を次に示します。

DefaultHttpClient defaultHttpClient = new DefaultHttpClient();

HttpGet method = new HttpGet(new URI("http://foo.com"));
HttpResponse response = defaultHttpClient.execute(method);
InputStream data = response.getEntity().getContent();
//Now we use the input stream remember to close it ....
于 2011-03-23T20:04:22.917 に答える
0

Googleドキュメントから

public DefaultHttpClient (ClientConnectionManager conman, HttpParams params)

パラメータと接続マネージャから新しいHTTPクライアントを作成します。

パラメータ
"conman" 接続マネージャ、
"params" パラメータ

public DefaultHttpClient (HttpParams params)
public DefaultHttpClient ()
于 2011-03-23T19:56:44.310 に答える