我试图将一些JSON值发布到我的mysql表中,但我一直得到JSONException of (End of input at character 0 of)。我试过用postman,它工作得很好,但当我试图在我的andriod设备上运行它时,我得到了这个错误,以下是我的java代码。
String url = "//MY url goes here//";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, response -> {
try {
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("message");
Toast.makeText(getAplicationContext, request_type + " " +success, Toast.LENGTH_SHORT).show();
progressBar1.setVisibility(View.INVISIBLE);
if (success.equals("Request sent Successfully")) {
Toast.makeText(getAplicationContext.this, request_type +" Request Sent Successfully", Toast.LENGTH_SHORT).show();
progressBar1.setVisibility(View.INVISIBLE);
} else {
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Exception " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}, error -> Toast.makeText(getApplicationContext(), "Error :: " + error.getMessage(), Toast.LENGTH_SHORT).show()) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("status", status);
params.put("type", type);
params.put("req", request);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
我能够使用postman成功地将数据发布到它,但它在android中抛出JsonException错误,所以我想这一定是来自我的上述代码。
我建议你看看API的postman响应,并断言它返回一个正确的json对象,你期待。E.g. 'message' key可以是一个对象,而不是字符串,即jsonObject.getJSONObject("message")另外,考虑使用google的gson库来解析POJOs的响应。
比如
if (callBack == null) {
throw new IllegalArgumentException("Callback cannot be null!!!");
}
HashMap<String, String> params = new HashMap<>();
params.put("status", status);
params.put("type", type);
params.put("req", request);
RequestQueue requestQueue = Volley.newRequestQueue(_context);
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST, URL, new JSONObject(params),
new com.android.volley.Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
RespObj retObj = gson.fromJson(response.toString(), RespObj.class);
callBack.onResponse(retObj)
}, new com.android.volley.Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}) {
@Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
@Override
public Map<String, String> getHeaders() {
return headers;
}
};
jsonObjReq.setRetryPolicy(policy);
jsonObjReq.setTag(tag);
requestQueue.add(jsonObjReq);
/*pojo*/
public class RespObj{
private String message;
public String getMessage(){
return message;
}
/**add this to gradle*/
implementation 'com.google.code.gson:gson:2.8.5'
}