1

HttpPutAndroidで認証を使用してリクエストを作成するにはどうすればよいですか?

(私はを使用して回避しようとしています。HttpURLConnectionこれは(少なくともAndroid 2.2では)深刻なバグがあるようですが、GET正常に動作します。配列のJSON表現を送信したいのですが、を使用して正しいクレデンシャルを設定していPasswordAuthenticationます。)

4

2 に答える 2

3

まず、認証トークンが必要です。そして、この行を追加するだけです。

httpGet.setHeader("Authorization", "Bearer " + yourToken);
于 2011-08-18T09:06:04.317 に答える
0

これが1つの一般的な解決策です。

HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, this.CONNECT_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpParameters, this.CONNECT_TIMEOUT);

DefaultHttpClient client = new DefaultHttpClient(httpParameters);

// Retrieve user credentials.
SharedPreferences settings = context.getSharedPreferences("LOGIN", 0);
String loginNameString = settings.getString("login_name", null);
String passwordString = settings.getString("password", null);

UsernamePasswordCredentials credentials = 
             new UsernamePasswordCredentials(loginNameString, passwordString);
AuthScope authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT);
             client.getCredentialsProvider().setCredentials(authScope, 
                                                              credentials);

HttpPut put = new HttpPut(UPLOAD_URL);

try
{
    put.setEntity(new StringEntity(responseJSONArray.toString(),    
                       SERVER_PREFERRED_ENCODING));
    put.addHeader("Content-Type", "application/json");
    put.addHeader("Accept", "application/json");
    HttpResponse response = client.execute(put);

    // 200 type response.
    if (response.getStatusLine().getStatusCode() >= HttpStatus.SC_OK &&
    response.getStatusLine().getStatusCode() < HttpStatus.SC_MULTIPLE_CHOICES)
    {
      // Handle OK response etc........
    }
}
catch (Exception e)
{
}
于 2011-09-06T13:19:31.203 に答える