我试图让通过在Android凌空库中的HTTP POST请求。
其实,我想检索API返回给我的JSON对象。
API文档给我,这个工作要求卷曲:
curl -H "Authorization: Token $API_KEY" \
--header "Content-Type: application/json" \
--compressed \
--data @- \
https://api.idbus.com/v1/search <<JSON
{
"origin_id": 1,
"destination_id": 17,
"date": "2015-08-15",
"passengers": [
{ "id": 1, "age": 30 },
{ "id": 2, "age": 30 },
{ "id": 3, "age": 1 }
]
}
JSON
但我想将其转换为与排球的HTTP请求。
问题是,当我启动我的代码,我得到一个404错误,而卷曲请求工作。
我认为这个问题是来自我通过JSON对象到请求的方式。但我没有找到错误,我希望有人能帮帮我,谢谢你在前进!
这里是我的代码:
String url = "https://api.idbus.com/v1/search";
final JSONObject jsonBody = new JSONObject();
JSONArray passengers = new JSONArray();
try {
passengers.put(getPerson(1, 30));
passengers.put(getPerson(2, 30));
passengers.put(getPerson(3, 1));
} catch (JSONException e){
e.printStackTrace();
}
try {
jsonBody.put("origin_id", 1);
jsonBody.put("destination_id", 17);
jsonBody.put("date", "2015-08-15");
jsonBody.put("passengers", passengers);
} catch (JSONException e){
e.printStackTrace();
}
JsonObjectRequest stringRequest = new JsonObjectRequest(Request.Method.POST, url, jsonBody,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
mTextView.setText(response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
mTextView.setText("That didn't work!");
}
}){
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("Authorization", "Token EnVo01jqN2XJIAd8vlLkw");
params.put("Content-Type","application/json");
return params;
}
};
queue.add(stringRequest);
}
JSONObject getPerson(int id, int age) throws JSONException {
JSONObject person = new JSONObject();
person.put("id", id);
person.put("age", age);
return person;
}
我的JSON对象是这样的:
{
"origin_id":1,
"destination_id":17,
"date":"2015-08-15",
"passengers":[
{
"id":1,
"age":30
},
{
"id":2,
"age":30
},
{
"id":3,
"age":1
}
]
}
尝试从final
失去jsonBody
的JSONObject
编辑:
您发送int类型为字符串,所以对对方服务器也许就不会那么乐意了:你送什么:
{"origin_id":"1",
"destination_id":"17",
"date":"2015-08-15",
"passengers":[{"id":"1","age":"30"},{"id":"2","age":"30"},{"id":"3","age":"1"}]}
你应该送:
{"origin_id":1,
"destination_id":17,
"date":"2015-08-15",
"passengers":[{"id":1,"age":30},{"id":2,"age":30},{"id":3,"age":1}]}
采用:
try {
passengers.put(getPerson(1, 30));
passengers.put(getPerson(2, 30));
passengers.put(getPerson(3, 1));
} catch (JSONException e){
e.printStackTrace();
}
try {
jsonBody.put("origin_id", 1);
jsonBody.put("destination_id", 17);
jsonBody.put("date", "2015-08-15");
jsonBody.put("passengers", passengers);
} catch (JSONException e){
e.printStackTrace();
}
而getPerson
现在看起来应该使用的,而不是为int
和String
id
age
:
JSONObject getPerson(int id, int age) throws JSONException
编辑2 - 什么工作
嗯,请尝试使用邮差(getpostman.com),并提交从那里同岗看到,抛出什么样的错误你,事情可能是一个服务器端的问题
params.put("Authorization", "Token EnVo01jqN2XJIAd8vlLkw");
删除Token
文本:
params.put("Authorization", "EnVo01jqN2XJIAd8vlLkw");