Wol*_*ane 8 java rest android android-volley
我是Volley和Android的新手.下面是我正在尝试执行的代码片段(Android使用Volley),但它是服务器返回400.使用另一个REST客户端完美地工作.这是使用PUT方法向服务器发出的请求.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
sendRequest();
}
private void sendRequest() {
RequestQueue queue = Volley.newRequestQueue(this);
final JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("password", "ttttt");
jsonObject.put("username", "tester3");
jsonObject.put("token", "blah");
} catch (JSONException e) {
// handle exception
}
JsonObjectRequest putRequest = new JsonObjectRequest(Request.Method.PUT, url, jsonObject,
new Response.Listener<JSONObject>()
{
@Override
public void onResponse(JSONObject response) {
// response
Log.d("Response", response.toString());
}
},
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", error.toString());
}
}
) {
@Override
public Map<String, String> getHeaders()
{
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
headers.put("Accept", "application/json");
return headers;
}
@Override
public byte[] getBody() {
try {
Log.i("json", jsonObject.toString());
return jsonObject.toString().getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
};
queue.add(putRequest);
}
Run Code Online (Sandbox Code Playgroud)
当我执行此代码时,我总是得到400 Bad请求,我无法弄清楚原因.使用像Postman这样的其他客户端,它按预期工作.这是邮递员的要求:
原始请求:
{"token":"blah","password":"ttttt","username":"tester3"}
Headers: Content-Type: application/json
Run Code Online (Sandbox Code Playgroud)
我不明白这个请求有什么问题我希望有人可以指出我做错了什么?
有时,在 getHeaders() 中添加标题“Content-Type”、“application/json”不会更好地覆盖 getBodyContentType() 并在此处返回标题。
所以随着,
public Map<String, String> getHeaders()
{
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
return headers;
}
Run Code Online (Sandbox Code Playgroud)
还补充说,
@Override
public String getBodyContentType() {
return "application/json";
}
Run Code Online (Sandbox Code Playgroud)
这在使用 POST 时对我有用。
小智 -6
我花了很多时间寻找如何做到这一点。对我有用的事情正在改变
Request.Method.PUT
Run Code Online (Sandbox Code Playgroud)
到
Request.Method.POST
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10486 次 |
| 最近记录: |