Volley 中的 POST 请求(使用 JSON 而不是字符串)
Posted
技术标签:
【中文标题】Volley 中的 POST 请求(使用 JSON 而不是字符串)【英文标题】:POST Request in Volley(using JSON instead of String) 【发布时间】:2019-03-18 10:23:53 【问题描述】:我正在开发一个应用程序,我可以在其中找到汽车的起点和目的地并将其发送到服务器。
我知道如何使用 volley 发送字符串,但是我发现很难以 JSON 格式发送数据。
部分代码如下:
b
tnFindPath.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
RequestQueue queue = Volley.newRequestQueue(MapsActivity.this);
String url = "http://192.168.43.162:8080/";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
@Override
public void onResponse(String response)
, new Response.ErrorListener()
@Override
public void onErrorResponse(VolleyError error)
)
//adding parameters to the request
@Override
protected Map<String, String> getParams() throws AuthFailureError
Map<String, String> params = new HashMap<>();
params.put("origin", etOrigin.getText().toString());
params.put("destination", etDestination.getText().toString());
return params;
;
// Add the request to the RequestQueue.
queue.add(stringRequest);
【问题讨论】:
android Volley post json data to server的可能重复 【参考方案1】:试试这个
final String httpUrl = //your url
try
JSONArray parameters = new JSONArray();
JSONObject jsonObject = new JSONObject();
jsonObject.put(Key,value);
jsonObject.put(Key,value);
parameters.put(jsonObject);
Log.i(TAG,parameters.toString());
JsonArrayRequest arrayRequest = new JsonArrayRequest(Request.Method.POST, httpUrl, parametersForphp,
new Response.Listener<JSONArray>()
@Override
public void onResponse(JSONArray response)
Log.d(TAG,response.toString());
try
//your code
catch (JSONException e)
e.printStackTrace();
, new Response.ErrorListener()
@Override
public void onErrorResponse(VolleyError error)
error.printStackTrace();
);
RequestQueueSingleton.getInstance(getApplicationContext()).addToRequestQueue(arrayRequest);
catch (Exception e)
e.printStackTrace();
【讨论】:
以上是关于Volley 中的 POST 请求(使用 JSON 而不是字符串)的主要内容,如果未能解决你的问题,请参考以下文章
Volley Android中带有JSON正文的POST请求
带有标头和原始 json 正文的 Volley POST 请求
android volley stringrequest post中的getparams怎么把json数据提交上去
Volley Post 请求在 onResponse 内没有返回响应