使用 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 时,调用 POSTs 但没有传递参数,当我使用 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
解决方案
解决方案是将字符串请求中的内容类型更改为 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屋!