如何在Android Java中使用Volley发送带JSON原始请求体的POST请求?
解决Volley发送JSON原始请求体的问题
你当前的问题在于,StringRequest的getParams()方法默认按application/x-www-form-urlencoded格式发送表单数据,但你的接口需要application/json格式的原始JSON请求体,必须通过重写getBody()和getBodyContentType()来实现需求。
具体修改方案
- 将请求参数转换为JSON字符串(推荐用Gson库简化操作)
- 重写
getBody()方法返回JSON字符串的字节数组 - 重写
getBodyContentType()指定请求内容类型为application/json; charset=utf-8
修改后的ApiService.class代码
import com.google.gson.Gson; // 保留你原有的其他导入类 public void sendTest(String token, final TestConfig config) { // 构造请求参数集合 HashMap<String, Object> paramsMap = new HashMap<>(); paramsMap.put("title", "hi"); paramsMap.put("address", "address1"); paramsMap.put("price", "200000"); paramsMap.put("region", new Integer[]{6, 8}); // 直接用数组,Gson会自动转为JSON数组格式 // 转换为JSON字符串 String requestBody = new Gson().toJson(paramsMap); StringRequest stringRequest = new StringRequest(Request.Method.POST, "https://.test.ir/public/api/v3/PropertyAssignment", new Response.Listener<String>() { @Override public void onResponse(String response) { config.onReceived(response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { if (error instanceof NoConnectionError || error instanceof TimeoutError) { context.startActivity(new Intent(context, NoInternet.class)); } config.onError(error.getMessage()); } }) { @Override public Map<String, String> getHeaders() throws AuthFailureError { HashMap<String, String> headers = new HashMap<>(); headers.put(Vars.KEY_AUTH, token); headers.put(Vars.KEY_USERNAME, Vars.USERNAME); headers.put(Vars.KEY_PASSWORD, Vars.PASSWORD); return headers; } @Override public String getBodyContentType() { return "application/json; charset=utf-8"; } @Override public byte[] getBody() throws AuthFailureError { try { return requestBody.getBytes("utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return null; } } }; RequestQueue requestQueue = Volley.newRequestQueue(context); requestQueue.add(stringRequest); }
依赖补充(若未引入Gson)
在模块级build.gradle中添加Gson依赖:
dependencies { // 保留你原有的其他依赖 implementation 'com.google.code.gson:gson:2.10.1' }
原方法无效的原因
getParams()是Volley为表单提交设计的方法,它会把Map中的键值对拼接成key1=value1&key2=value2的格式,并自动设置Content-Type为application/x-www-form-urlencoded,和接口期望的JSON请求体格式不匹配,因此无法被正确解析。
内容的提问来源于stack exchange,提问作者Amin Azizzadeh
相关产品推荐
相关产品推荐

