1
您如何在Android上編寫HttpPut
請求進行身份驗證?我想嘗試使用HttpURLConnection
,這似乎是嚴重的錯誤(至少在Android 2.2中),但GET
工作正常。我想發送一個數組的JSON表示,我有正確的憑證已使用PasswordAuthentication
設置。)Android和經過身份驗證的HttpPut帶有JSON主體
您如何在Android上編寫HttpPut
請求進行身份驗證?我想嘗試使用HttpURLConnection
,這似乎是嚴重的錯誤(至少在Android 2.2中),但GET
工作正常。我想發送一個數組的JSON表示,我有正確的憑證已使用PasswordAuthentication
設置。)Android和經過身份驗證的HttpPut帶有JSON主體
這是一個通用的解決方案。
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)
{
}
首先,您需要擁有身份驗證令牌。然後只需添加這一行。
httpGet.setHeader("Authorization", "Bearer " + yourToken);
保存我的一天!我認爲承載者應該是關鍵的一部分......將它移到這個值可以節省我的調試時間! – benchuk