[英]How to ensure that header request are sent when using Volley
我正在嘗試使用Volley在我的Android應用程序中調用RESTful API。 該API要求用戶使用公共密鑰和將通過http標頭發送的哈希進行身份驗證。
當我嘗試發送帶有公鑰和哈希的標頭的POST請求時,我發現標頭未由服務器附加/接收,並且出現Volley錯誤-BasicNetwork.performRequest:意外的響應代碼400
這是我嘗試使用JSON發送帶有請求參數的標頭請求的方法。
HashMap<String, String> params = new HashMap<String, String>();
params.put("email", email.getText().toString());
params.put("password", password.getText().toString());
pDialog = new ProgressDialog(LoginActivity.this);
pDialog.setMessage("Logging in...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
RequestQueue requestQueue = VolleySingleton.getInstance().getRequestQueue();
JsonObjectRequest request = new JsonObjectRequest(ApplicationConstants.url_sign_in, new JSONObject
(params), new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
Log.d(TAG, "onResponse") ;
error = response.getBoolean(TAG_ERROR);
message = response.getString(TAG_MESSAGE);
Toast.makeText(LoginActivity.this, message + " value of error", Toast.LENGTH_LONG).show();
pDialog.cancel();
} catch (JSONException e) {
e.printStackTrace();
}
Toast.makeText(LoginActivity.this, message, Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG,"onErrorResponse()") ;
pDialog.cancel();
NetworkResponse networkResponse = error.networkResponse;
if (networkResponse != null && networkResponse.statusCode == HttpStatus.SC_UNAUTHORIZED) {
// HTTP Status Code: 401 Unauthorized
Toast.makeText(LoginActivity.this, message, Toast.LENGTH_SHORT).show();
}
}
}){
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put(ApplicationConstants.publicKey, "Yahoo");
headers.put(ApplicationConstants.hash, "Google");
Log.d(TAG,"getHeaders()") ;
return headers;
}
};
requestQueue.add(request);
ApplicationConstants類
public interface ApplicationConstants {
//String ip = "10.0.3.2";
String ip = "192.168.100.2";
String publicKey = "pskPublicKey";
String hash = "pskPublicKey";
如果我僅使用請求參數嘗試運行,但是當我嘗試發送頭請求時,它將無法發送頭請求。
正如您在圖片中看到的那樣,我在郵遞員中提供了公鑰和哈希,我還從android的標頭中發送了數據,但服務器中未接收到數據
400表示對服務器的錯誤請求。 標題可能是錯誤的。 您可以嘗試添加Content-Type=application/json
標頭,如下所示
header.put("Content-Type", "application/json");
如果這不起作用,則應在REST客戶端中嘗試該請求,並查看該請求是否適用於給定的標頭。 在嘗試中斷Android之前,請確保該請求在其余客戶端上正常運行。
覆蓋您的getBodyContentType
方法
public String getBodyContentType()
{
return "application/json";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.