Как вернуть JsonObject через getParams в Volley, Android?
Хочу отправить json на сервер в таком формате:
{"name":"apiName","param":{}}
Я использую библиотеку Volley и переопределяю метод getParams таким образом:
protected Map<String, String> getParams() throws AuthFailureError
{
}
В этом методе создаю два json objects:
JSONObject jsonObject = new JSONObject();
JSONObject jsonObject2 = new JSONObject();
try
{
jsonObject.put("name", "apiName");
jsonObject.put("param", jsonObject2);
}
catch (JSONException e)
{
e.printStackTrace();
}
Каким образом я могу отправить объект с использованием или без использования getParams?
Ответы (2 шт):
Автор решения: Andrew
→ Ссылка
Можно попробовать таким способом:
RequestQueue queue = Volley.newRequestQueue(this);
private void makeJsonObjReq() {
showProgressDialog();
Map<String, String> postParam= new HashMap<String, String>();
postParam.put("un", "[email protected]");
postParam.put("p", "somepasswordhere");
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
Const.URL_LOGIN, new JSONObject(postParam),
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
msgResponse.setText(response.toString());
hideProgressDialog();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hideProgressDialog();
}
}) {
/**
* Passing some request headers
* */
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
};
jsonObjReq.setTag(TAG);
// Adding request to request queue
queue.add(jsonObjReq);
// Cancelling request
/* if (queue!= null) {
queue.cancelAll(TAG);
} */
}
Автор решения: DenVebber
→ Ссылка
Решил так:
final String jsonString = jsonObject.toString();
@Override
public byte[] getBody() throws AuthFailureError
{
try { return jsonString == null ? null : jsonString.getBytes("utf-8"); }
catch (UnsupportedEncodingException ex) { return null; }
}