我尝试使用Android的Volley库来模拟以下cURL请求:
curl -H "Content-Type: application/json" -X GET -d '{"password":"password"}' https://0.0.0.0:5000/staging/api/v2.0/supporter/name=Steven
按预期工作,但以下代码不适用于android:
public void getSupporterByName(String name, String password, @NonNull final APIRequestCallback<Supporter> callback){
try {
JSONObject job = new JSONObject();
job.put("password", password);
JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET, getAPIEndpoint() + "supporter/name=" + name, job, new Response.Listener<JSONObject>() {
@Override public void onResponse(JSONObject response) {
callback.onSuccess(parseSupporter(response.toString()));
}
}, new Response.ErrorListener() {
@Override public void onErrorResponse(VolleyError error) {
callback.onFailure(error);
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> currs = super.getHeaders();
Map<String, String> map = currs != null ? new HashMap<>(super.getHeaders()) : new HashMap<String, String>();
map.put("Content-Type", "application/json");
return map;
}
};
requestQueue.add(req);
} catch (Exception ex) {
callback.onFailure(ex);
}
}
我不断从API收到400错误请求,我知道这是因为API没有看到发送过的JSONObject,因此无法验证密码。有没有办法使用Volley使用JSON主体发出GET
请求?
答案 0 :(得分:1)
我的问题或多或少归结为这个问题:Proper way to send username and password from client to server
根据建议,我使用了POST请求而不是GET。