我正在使用 Volley Android 将一些数据发布到 Restful Api 端点,使用 postman 它可以在 raw
和 application/json
中处理很好的 body 数据,例如:
{
"operation": "someaction",
"key": "pk_test_fssdfsdfjkhkjsdhf84334",
"token": "tk_test_432332sdxxaJJJJHHHshhsas",
"ssids":[[{
"mac":"34:15:13:d4:59:f1" //<--this is important here, it's mac addr
}]] //<-- yup, with double double [[ ... ]]
}
当我在下面的代码中使用 volley 时,问题就开始了:
public void getBleeCardData(Response.Listener<String> response, final String ssidsdata, final ProgressDialog pd)throws JSONException {
String url = "https://www......com/api/something.do";
JSONObject jsonBody = new JSONObject();
jsonBody.put("operation", "something");
jsonBody.put("key", "pk_try_oqiwFHFKjkj4XMrh");
jsonBody.put("token", "tk_tkn_erwweelWgH4olfk2");
jsonBody.put("ssids", ssidsdata.toLowerCase());
final String mRequestBody = jsonBody.toString();
RequestQueue queue = Volley.newRequestQueue(context);
StringRequest postRequest = new StringRequest(Request.Method.POST, url,new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d("Response", response);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("ERROR", "error => " + error.toString());
}
}
) {
@Override
public byte[] getBody() throws AuthFailureError {
try {
return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", mRequestBody, "utf-8");
return null;
}
}
@Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}
};
queue.add(postRequest.setRetryPolicy(new DefaultRetryPolicy(30000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT))); }
我需要编码方面的帮助,使用 Volley 发送的数据如下:
{"operation":"dataMachines","key":"pk_test_6pRNAHGGoqiwFHFKjkj4XMrh","token":"tk_test_ZQokik736473jklWgH4olfk2","ssids":"[[{\"mac\":\"34:15:13: d4:59:f1\"}]]"}
为什么发送这个节点像 "ssids":"[[{\"mac\":\"34:15:13:d4:59:f1\"}]]"}
像这样?,“\”
,一些特殊的编码来删除它呢?
是否可以更改编码以防止那些"\"
?
最佳答案
创建一个 JsonObjectRequest
JSONObject jsonBody = new JSONObject();
jsonBody.put("operation", "something");
jsonBody.put("key", "pk_try_oqiwFHFKjkj4XMrh");
jsonBody.put("token", "tk_tkn_erwweelWgH4olfk2");
jsonBody.put("ssids", ssidsdata.toLowerCase());
JsonObjectRequest jobReq = new JsonObjectRequest(Request.Method.POST, url, jsonBody,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject jsonObject) {
//Log.d("Responses", jsonObject.toString());
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
//Log.e("responses", volleyError.toString());
}
});
如果您要发送 JSONArray,则使用 JsonArrayRequest 而不是 JsonObjectRequest
关于java - Android Volley POST - 正文中的 JSON 编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47505742/