android - 如何使用 JsonObjectRequest with volley 在 json 对象中发送包含 json 数组的 Json 数据

标签 android jsonobjectrequest

    String url_save = "http://13.210.238.81:8080/freelance-api/gig/addGig";

    RequestQueue requestQueue = Volley.newRequestQueue(this);

    JSONObject obj=new JSONObject();
    try {
        obj.put("categoryId",categoryId);
        obj.put("gigDescription",edt_describeProject.getText().toString());
        obj.put("revision",edt_revision.getText().toString());
        obj.put("gigRate",edt_rate.getText().toString());
        obj.put("expectedDuration",expected_delivery.getSelectedItem().toString());

        obj.put("gigTitle",edt_uniqueTitle.getText().toString());
        obj.put("subCategoryId",sub_Category);

        JSONArray array=new JSONArray();
        JSONObject objp=new JSONObject();
        objp.put("skillId",id);
        objp.put("skillTitle",edt_skills.getQuery().toString());
        array.put(objp);
        obj.put("gigSkills",array);

    } catch (JSONException e) {
        e.printStackTrace();
    }

    final String requestBody = obj.toString();

    Toast.makeText(getApplicationContext(), "params-"+obj, Toast.LENGTH_LONG).show();
    Log.d("params", ""+obj);




    /*final Map<String, String> params = new HashMap<String, String>();
    params.put("categoryId", categoryId);
    params.put("gigDescription",edt_describeProject.getText().toString());
    params.put("skillTitle",edt_skills.getQuery().toString());
    params.put("skillId",id);
    params.put("gigTitle",edt_uniqueTitle.getText().toString());
    params.put("subCategoryId",sub_Category);
    params.put("expectedDuration",expected_delivery.getSelectedItem().toString());
    params.put("revision",edt_revision.getText().toString());
    params.put("gigRate",edt_rate.getText().toString());
    Toast.makeText(getApplicationContext(), "params-"+params, Toast.LENGTH_LONG).show();

    Log.d("params", ""+params);*/

    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,url_save,new JSONObject(requestBody), new Response.Listener<JSONObject>() {


        @Override
        public void onResponse(JSONObject response) {

            Toast.makeText(getApplicationContext(),
                    "response-"+response, Toast.LENGTH_LONG).show();
            Log.d("response",""+response);

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

            Toast.makeText(getApplicationContext(),
                    "error"+error.toString(), Toast.LENGTH_LONG).show();
            Log.d("VolleyError","Volley"+error);
            VolleyLog.d("JSONPost", "Error: " + error.getMessage());

            NetworkResponse networkResponse = error.networkResponse;
            if (networkResponse != null && networkResponse.data != null) {
                Log.e("Status code", String.valueOf(networkResponse.data));
            }

            /*if (error.networkResponse == null) {
                if (error.getClass().equals(TimeoutError.class)) {
                    Toast.makeText(getApplicationContext(),
                            "Failed to save. Please try again.", Toast.LENGTH_LONG).show();
                }
            }*/

        }
    }){
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {

            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "applications/json");
            headers.put("Authorization", "Bearer"+" "+sharedPreferenceConfig.ReadToken(getString(R.string.token_preference)));
            return headers;
        }
        /*@Override
        public byte[] getBody() {
            try {
                return requestBody == null ? null : requestBody.getBytes("utf-8");
            } catch (UnsupportedEncodingException uee) {
                VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
                return null;
            }

        }*/
        @Override
        public String getBodyContentType() {
            return "application/json; charset=utf-8";
        }


    };

    requestQueue.add(jsonObjectRequest);

Json 数据看起来像下面想要使用 JsonObjectRequest 将数据发送到服务器。

{
    "categoryId":"3",
    "gigDescription":"test",
    "revision":"3",
    "gigRate":"20",
    "expectedDuration":"10",
    "gigTitle":"test",
    "subCategoryId":"10",
    "gigSkills":
    [
        {
            "skillId":"1",
            "skillTitle":"Javaaa"

        }
    ]

} 

最佳答案

您可以像这样检查 volly 错误的状态代码。它会告诉您为什么会收到 com.android.volley.ClientError

NetworkResponse response = error.networkResponse;

   if (response != null && response.data != null) {

         switch (response.statusCode) {
            case 401:
               //Session expired or token expired
            break;
            case 400:

            break;
          }
   }

关于android - 如何使用 JsonObjectRequest with volley 在 json 对象中发送包含 json 数组的 Json 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54212795/

相关文章:

android - 如何在 android 的节电模式下播放动画?有什么解决办法吗?

java - 在 Android 中每 10 分钟调用一个方法

java - 使用 volley 获取 JSON 响应 - Android Studio

java - 方法未按时间顺序调用

android - 如何使用 Volley 将 JSONObject 作为表单数据发送到服务器

安卓 10 : fetch the gallery via MediaStore with location information

android - 如何在 Kotlin 中发出 API 请求?

android - 更新Android Studio 3.0.1后无法构建Gradle