4

私はこれまでにこのコードを持っています:

private class DownloadWebPageTask extends AsyncTask<String, Void, String> 
{
        @Override
        protected String doInBackground(String... theParams) 
        {
            String myUrl = theParams[0];
            String myEmail = theParams[1];
            String myPassword = theParams[2];

            HttpPost post = new HttpPost(myUrl);
            post.addHeader("Authorization","Basic "+ Base64.encodeToString((myEmail+":"+myPassword).getBytes(), 0 ));
            ResponseHandler<String> responseHandler = new BasicResponseHandler();

            String response = null;

            try 
            {
                    response = client.execute(post, responseHandler);
                InputStream content = execute.getEntity().getContent();

                BufferedReader buffer = new BufferedReader(
                            new InputStreamReader(content));
                    String s = "";
                    while ((s = buffer.readLine()) != null) 
                    {
                        response += s;
                    }
                } 
                catch (Exception e) 
                {
                    e.printStackTrace();
                }

            return response;
        }


        @Override
        protected void onPostExecute(String result) 
        {
            }

}

次の時点で混乱しているため、このコードはコンパイルされません。

                response = client.execute(post, responseHandler);
                InputStream content = execute.getEntity().getContent();

さまざまな例をいじってそのコードを取得しましたが、クライアントがどのオブジェクトであるべきか、最初の行がサーバーの応答を取得するだけなのか、それとも InputStream を取得してサーバーを読み取るルートをたどる必要があるのか​​ わかりませんで応答しますか?

これを正しく行う方法を理解するのを手伝ってください。

ありがとうございました!

4

3 に答える 3

3

に切り替えることをお勧めしHttpURLConnectionます。この記事によると、その API は よりもシンプルでHttpClient、Android でのサポートが優れています。を使用することを選択した場合HttpURLConnection、認証は非常に簡単です。

Authenticator.setDefault(new Authenticator() {
    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication("username", "password".toCharArray());
    }
});

その後、HttpURLConnection通常通りご使用ください。簡単な例:

final URL url = new URL("http://example.com/");
final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
final InputStream is = conn.getInputStream();
final byte[] buffer = new byte[8196];
int readCount;
final StringBuilder builder = new StringBuilder();
while ((readCount = is.read(buffer)) > -1) {
    builder.append(new String(buffer, 0, readCount));
}
final String response = builder.toString();
于 2012-02-28T15:32:09.857 に答える
3

HttpClientAndroid に同梱されているApache のバージョンは、ベータ版以前の古いバージョンのHttpClient. Google はこれを使用しないことを長い間推奨しており、Android 6.0 で削除しました。Google の代替品HttpURLConnection は HTTP ダイジェスト認証をサポートせず、ベーシックのみをサポートします。

これにより、次のようないくつかのオプションが残ります。

  • HttpURLConnection(Google が推奨するように) に移行し、ダイジェスト認証用のライブラリ、 bare-bones-digestを使用します。以下の例。
  • またはの代わりにOkHttpライブラリを使用します。OkHttp はそのままではダイジェストをサポートしていませんが、ダイジェスト認証子を実装するライブラリokhttp-digestがあります。以下の例。HttpURLConnectionHttpClient
  • Android 6.0の変更リストに記載されているように、ライブラリをビルドにHttpClient明示的に追加して、(非推奨) を引き続き使用します。'org.apache.http.legacy'
  • の新しいバージョンHttpClientを Android に移植するための Apache プロジェクトがありますが、このプロジェクトは廃止されました。詳細については、Apache の HttpClient for Android のページを参照してください
  • HTTP ダイジェストを自分で実装します。

以下は、 bare-bones-digestを使用してリクエストを認証する方法の詳細な例ですHttpURLConnection(プロジェクトの github ページからコピー):

// Step 1. Create the connection
URL url = new URL("http://httpbin.org/digest-auth/auth/user/passwd");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();

// Step 2. Make the request and check to see if the response contains
// an authorization challenge
if (connection.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
    // Step 3. Create a authentication object from the challenge...
    DigestAuthentication auth = DigestAuthentication.fromResponse(connection);
    // ...with correct credentials
    auth.username("user").password("passwd");

    // Step 4 (Optional). Check if the challenge was a digest
    // challenge of a supported type
    if (!auth.canRespond()) {
        // No digest challenge or a challenge of an unsupported
        // type - do something else or fail
        return;
    }

    // Step 5. Create a new connection, identical to the original
    // one..
    connection = (HttpURLConnection) url.openConnection();
    // ...and set the Authorization header on the request, with the
    // challenge response
    connection.setRequestProperty(
        DigestChallengeResponse.HTTP_HEADER_AUTHORIZATION,
        auth.getAuthorizationForRequest("GET", connection.getURL().getPath()));
}

以下はOkHttpokhttp-digestを使用した例です(okhttp-digest ページからコピー):

client = new OkHttpClient();
final DigestAuthenticator authenticator = new DigestAuthenticator(new Credentials("username", "pass"));

final Map<String, CachingAuthenticator> authCache = new ConcurrentHashMap<>();
client.interceptors().add(new AuthenticationCacheInterceptor(authCache));
client.setAuthenticator(new CachingAuthenticatorDecorator(authenticator, authCache));

Request request = new Request.Builder()
  .url(url);
  .get()
  .build();
Response response = client.newCall(request).execute();
于 2016-10-20T06:42:10.593 に答える