我尝试通过Volley发布JSON请求并收到错误 BasicNetwork.performRequest:意外的响应代码500 此API URL已在POSTMAN中经过测试,可以通过IOS版本的应用程序调用。
我怀疑标头值未添加到我的代码中(如果我输入错误,请纠正我)
我试图在代码中添加getHeaders()
函数,但似乎无法正常工作。有人可以告诉我如何解决这个问题吗?
这是我当前的代码:-
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.clipped_product_page)
setTitle("Clipped Product")
val actionbar = supportActionBar
actionbar?.setDisplayHomeAsUpEnabled(true)
actionbar?.setDisplayHomeAsUpEnabled(true)
val URL = "https://api.sample.com/Api/user_id"
val json = JSONObject()
json.put("user_id", "1")
json.put("code", "AB")
val jsonOblect = object : JsonObjectRequest(
Request.Method.POST,
URL,
json,
Response.Listener {response ->
// Get your json response and convert it to whatever you want.
Toast.makeText(this, "You Clicked: $response", Toast.LENGTH_SHORT).show()
},
Response.ErrorListener {
Toast.makeText(this, "Error $it .message", Toast.LENGTH_SHORT).show()
}
) {
@Throws(AuthFailureError::class)
override fun getHeaders(): Map<String, String> {
val headers = HashMap<String, String>()
headers.put("Content-Type", "application/json")
return headers
}
}
VolleySingleton.getInstance(this).addToRequestQueue(jsonOblect)
}
我该如何实现并将输出转换为数组列表?
请帮助谢谢。
答案 0 :(得分:1)
要通过Volley发送帖子请求
String URL = "";
JSONObject json = new JSONObject();
json.put("email", "abc@abc.com");
json.put("password", "");
json.put("user_type", "");
JsonObjectRequest jsonOblect = new JsonObjectRequest(Request.Method.POST, URL, json, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
// Get your json response and convert it to whatever you want.
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// Error
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
final Map<String, String> headers = new HashMap<>();
headers.put("Authorization", "TOKEN");//put your token here
return headers;
}
};
VolleyApplication.getInstance().addToRequestQueue(jsonOblect);
答案 1 :(得分:0)
最后,我通过使用以下示例代码解决了我的问题:-
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.clipped_product_page)
setTitle("Clipped Product")
val actionbar = supportActionBar
actionbar?.setDisplayHomeAsUpEnabled(true)
actionbar?.setDisplayHomeAsUpEnabled(true)
val URL = "https://api.sample.com/Api/user_id"
val stringRequest = object : StringRequest(Request.Method.POST, URL,
Response.Listener { response -> Toast.makeText(this, response, Toast.LENGTH_LONG).show() },
Response.ErrorListener { error -> Toast.makeText(this, error.toString(), Toast.LENGTH_LONG).show() }) {
override fun getParams(): Map<String, String> {
val params = HashMap<String, String>()
params["user_id"] = "7"
params["code"] = "MY"
return params
}
}
VolleySingleton.getInstance(this).addToRequestQueue(stringRequest)
}
我将 JsonObjectRequest更改为StringRequest