![](/img/trans.png)
[英]How to send post request using raw json with volley or retrofit in android
[英]Android Send POST of JSON raw body with volley
我必须发送带有 voley 的帖子,但是当我尝试按要求发送原始正文而不是响应时,出现此错误
******com.android.volley.ServerError******: {"message":"未收到用于注册的用户帐户数据。"}
我在邮递员中尝试了同样的方法,效果很好,我该如何在我的代码中修复它?
在邮递员中工作的原始身体 - >
{
"camp1": {
"value": "value"
},
"camp2": {
"value": "value2"
}
}
这就是我的代码中的内容->
public void requestRegistrationInfo(@NonNull final String camp1, @NonNull final String camp2,final Listener listener) {
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(new JsonObjectRequest(
Request.Method.POST, URL,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.v("IT WORK");
listener.onSuccess();
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("******" + error.toString() + "******", getErrorMessage(error));
listener.onFailure();
}
})
{
@Override
protected Map<String,String> getParams() {
Map<String, String> map = new HashMap<>();
map.put("{camp1", "value");
map.put("camp2", "value");
return map;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> map = new HashMap<>();
map.put("header1", "header1");
map.put("header2", "header2");
return map;
}
});
}
我该怎么做才能正确发送原始 json 并且不显示错误?
在正常情况下 JSONObject 请求没有命中 getParams() 方法,该方法仅用于 String 请求和传递键值对数据负载。 如果要传递带有 JSON 数据的原始正文,首先必须将数据格式化为服务器接受。 在您的情况下,这是您的数据
{
"camp1":{
"value":"value1"
},
"camp2":{
"value2":"value2"
}
}
您必须像这样将数据转换为服务器接受的 JSON 格式
JSONObject jsonObject = new JSONObject();
jsonObject.put("value", "value1");
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("value2", "value2");
JSONObject jsonObject2 = new JSONObject();
jsonObject2.put("camp1", jsonObject);
jsonObject2.put("camp2",jsonObject1);
//jsonObject2 is the payload to server here you can use JsonObjectRequest
String url="your custom url";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.POST,url, jsonObject2, new com.android.volley.Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
//TODO: Handle your response here
}
catch (Exception e){
e.printStackTrace();
}
System.out.print(response);
}
}, new com.android.volley.Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// TODO: Handle error
error.printStackTrace();
}
});
在我们将传递数据的 url 参数之后,JsonObjectRequest 将在其构造函数中接受有效负载为 json
try {
RequestQueue requestQueue = Volley.newRequestQueue(this);
String URL = "http://...";
JSONObject jsonBody = new JSONObject();
jsonBody.put("Title", "Android Volley Demo");
jsonBody.put("Author", "BNK");
final String requestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
}
}) {
@Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
@Override
public byte[] getBody() throws AuthFailureError {
try {
return requestBody == null ? null : encodeParameters(requestBody , getParamsEncoding());
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
return null;
}
}
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
// can get more details such as response.headers
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}
请检查编辑过的 getBody()
@Override
public byte[] getBody() throws AuthFailureError {
try {
return requestBody == null ? null : encodeParameters(requestBody , getParamsEncoding());
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
return null;
}
}
这是测试代码试试这个:
private void multipartRequestWithVolly() {
String urll = "your_url";
progressDialog.show();
StringRequest request = new StringRequest(Request.Method.POST, urll, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
progressDialog.dismiss();
if (!TextUtils.isEmpty(response)) {
Log.e(TAG, "onResponse: " + response);
textView.setText(response);
} else {
Log.e(TAG, "Response is null");
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Log.e(TAG, "onErrorResponse: " + error.toString());
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
hashMap = new HashMap<>();
hashMap.put("OPERATIONNAME", "bplan");
hashMap.put("mcode", "298225816992");
hashMap.put("deviceid", "dfb462ac78317846");
hashMap.put("loginip", "192.168.1.101");
hashMap.put("operatorid", "AT");
hashMap.put("circleid", "19");
return hashMap;
}
};
AppController.getInstance().addToRequestQueue(request);
}
如果您调用任何 REST-API,请注意该负载始终采用 JSON 格式。 因此,您可以像这样使用对象主体作为有效负载。
HashMap<String, String> params = new HashMap<String, String>();
params.put("username", input_loginId.getText().toString());
params.put("password", input_password.getText().toString());
你可以像这样在方法上传递这个
JsonObjectRequest logInAPIRequest = new JsonObjectRequest(Request.Method.POST, YOUR-URL,
new JSONObject(params), new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
input_errorText.setText(response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
input_errorText.setText("Error: " + error.getMessage());
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.