如何在Android上编写带有身份验证的HttpPut
请求?
(我正在尝试使用HttpURLConnection
,这似乎是严重的错误(至少在Android 2.2中),但GET
工作正常。我想发送一个JSON表示一个数组,我已经使用PasswordAuthentication
设置了正确的凭据。)
答案 0 :(得分:3)
首先,您需要拥有身份验证令牌。然后只需添加此行。
httpGet.setHeader("Authorization", "Bearer " + yourToken);
答案 1 :(得分: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)
{
}