通过Volley POST传递参数 [英] Pass Parameter with Volley POST
问题描述
我能够使用Postman和以下参数调用HTTP端点:
I was able to call an HTTP endpoint using Postman and these parameters:
{
"name":"Val",
"subject":"Test"
}
但是我无法通过Android在Volley上做同样的事情:这里正在尝试使用JSONRequest:
However I am unable to do the same with Volley through Android: Here is trying to use JSONRequest:
HashMap<String, String> params2 = new HashMap<String, String>();
params.put("name", "Val");
params.put("subject", "Test Subject");
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.POST, Constants.CLOUD_URL, new JSONObject(params2), new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
mView.showMessage("Response: " + response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
mView.showMessage(error.getMessage());
}
});
// Access the RequestQueue through your singleton class.
VolleySingleton.getInstance(mContext).addToRequestQueue(jsObjRequest);
这里正在尝试StringRequest
And here is trying StringRequest
private void postMessage(Context context, final String name, final String subject ){
RequestQueue queue = Volley.newRequestQueue(context);
StringRequest sr = new StringRequest(Request.Method.POST, Constants.CLOUD_URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
mView.showMessage(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}){
@Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("name", name);
params.put("subject", subject);
return params;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("Content-Type","application/x-www-form-urlencoded");
return params;
}
};
queue.add(sr);
}
当我使用JSONRequest时,调用POST却没有传递任何参数,而当我使用StringRequest时出现以下错误?如何将JSON数据传递给Volley通话?
When I use JSONRequest, the call POSTs but no parameter is passed and when I use StringRequest I get the error below? How can I pass JSON data to Volley call?
E/Volley: [13053] BasicNetwork.performRequest: Unexpected response code 400 for
这是处理请求的服务器代码
Here is the server code that handles the request
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
var helloRequest = await req.Content.ReadAsAsync<HelloRequest>();
var name = helloRequest?.Name ?? "world";
var responseMessage = $"Hello {personToGreet}!";
log.Info($"Message: {responseMessage}");
return req.CreateResponse(HttpStatusCode.OK, $"All went well.");
}
public class HelloRequest
{
public string Name { get; set; }
public string Subject { get; set; }
}
推荐答案
服务器代码期望JSON对象返回字符串,或者返回Json字符串.
The server code is expecting a JSON object is returning string or rather Json string.
JsonObjectRequest
JSONRequest在请求正文中发送一个JSON对象,并在响应中期望一个JSON对象.由于服务器返回一个字符串,因此最终抛出ParseError
JSONRequest sends a JSON object in the request body and expects a JSON object in the response. Since the server returns a string it ends up throwing ParseError
StringRequest
StringRequest发送主体类型为x-www-form-urlencoded
的请求,但是由于服务器需要JSON对象.您最终收到了400个错误的请求
StringRequest sends a request with body type x-www-form-urlencoded
but since the server is expecting a JSON object. You end up getting 400 Bad Request
解决方案
解决方案是将字符串请求中的content-type更改为JSON,并在正文中传递一个JSON对象.因为它已经期望一个字符串,所以您在这里的反应很好.该代码应如下所示.
The Solution is to change the content-type in the string request to JSON and also pass a JSON object in the body. Since it already expects a string you response you are good there. Code for that should be as follows.
StringRequest sr = new StringRequest(Request.Method.POST, Constants.CLOUD_URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
mView.showMessage(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
mView.showMessage(error.getMessage());
}
}) {
@Override
public byte[] getBody() throws AuthFailureError {
HashMap<String, String> params2 = new HashMap<String, String>();
params2.put("name", "Val");
params2.put("subject", "Test Subject");
return new JSONObject(params2).toString().getBytes();
}
@Override
public String getBodyContentType() {
return "application/json";
}
};
服务器代码中也存在一个错误
Also there is a bug here in the server code
var responseMessage = $"Hello {personToGreet}!";
应该
var responseMessage = $"Hello {name}!";
这篇关于通过Volley POST传递参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!