我有JSONObjectRequest
我试图通过Volley发送到我的Rails应用程序。我正在点击我的Rails API,但收到了401回复。我的API绝对可以通过curl工作,所以我认为我还没有形成我的Volley请求。
public void login(View button) {
EditText userEmailField = (EditText) findViewById(R.id.userEmail);
mUserEmail = userEmailField.getText().toString();
EditText userPasswordField = (EditText) findViewById(R.id.userPassword);
mUserPassword = userPasswordField.getText().toString();
if (mUserEmail.length() == 0 || mUserPassword.length() == 0) {
// input fields are empty
Toast.makeText(this, "Please complete all the fields",
Toast.LENGTH_LONG).show();
return;
} else {
JsonObjectRequest loginRequest = new JsonObjectRequest(Request.Method.POST, url, null,
new Response.Listener<JSONObject>() {
@Override public void onResponse(JSONObject response) {
try {
//everything is good
if (response.getBoolean("success")) {
SharedPreferences.Editor editor = mPreferences.edit();
//Save auth_token into shared preferences
editor.putString("AuthToken", response.getJSONObject("data").getString("auth_token"));
editor.commit();
// launch the HomeActivity and close this one
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
finish();
}
} catch (Exception e) {
// something went wrong: show Toast
//with the exception message
Toast.makeText(myActivity, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener()
{
@Override public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", error.toString());
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("email", mUserEmail);
params.put("password", mUserPassword);
return params;
}
};
VolleySingleton.getInstance(this).addToRequestQueue(loginRequest); //Call to get dashboard feed
}
};
修改
带有401的Rails日志:似乎我的参数不包含在请求中。在排球请求中我做错了什么,它不会被包括在内?
Started POST "/api/v1/sessions" for 11.111.111.11 at ....
Processing by Api::V1::SessionsController#create as JSON
Parameters: {"session"=>{}}
Completed 401 Unauthorized in 2ms
答案 0 :(得分:0)
感谢@jamesw指出我正确的方向here。出于某种原因,此POST请求中未调用getParams
。我不确定为什么,但显然其他人也有同样的问题。
解决方法是创建一个JSONObject并将其传递给JsonObjectRequest
:
JSONObject parentData = new JSONObject();
JSONObject childData = new JSONObject();
try {
childData.put("email", mUserEmail);
childData.put("password", mUserPassword);
parentData.put("user", childData);
} catch (JSONException e) {
e.printStackTrace();
}
将其传递给JOR构造函数:
JsonObjectRequest loginRequest = new JsonObjectRequest(Request.Method.POST, url, parentData, Listener..., ErrorListener...
适合我,但如果有人可以解释如何致电getParams()
或更清洁的解决方案,请随时回答,我会接受。