1

您如何HttpPut在 Android 上编写带有身份验证的请求?

(我正在尝试使用HttpURLConnection,这似乎有严重的错误(至少在 Android 2.2 中)但GET工作正常。我想发送一个数组的 JSON 表示,并且我已经使用 设置了正确的凭据PasswordAuthentication。)

4

2 回答 2

3

首先,您需要有一个身份验证令牌。然后只需添加这一行。

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

这是一个通用的解决方案。

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 回答