带有int,string和jsonobjects

时间:2017-01-30 20:52:40

标签: android json android-volley

最新消息

我正在尝试在我的服务器上发布JSONObject。

我尝试了一些我在堆栈中找到的代码:

        String url = "http://10.0.2.2:8080/order";
    try {
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        String URL = "http://10.0.2.2:8080/order";
        JSONObject jsonBody = new JSONObject();
        jsonBody.put("waiterId", 1);
        jsonBody.put("tableNumber", 4);
        jsonBody.put("remark", "asd");
        jsonBody.put("products", new JSONObject());
        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 : 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
            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();
    }

我收到错误:

  

E / Volley:[275] BasicNetwork.performRequest:http://10.0.2.2:8080/order的意外响应代码400   E / VOLLEY:com.android.volley.ServerError

或者这个:

    String url = "http://10.0.2.2:8080/order";
    JSONObject jsonObject = new JSONObject();
    try {
        jsonObject.put("waiterId", 1);
        jsonObject.put("tableNumber", 1);
        jsonObject.put("remark", "zamowienie");
        jsonObject.put("products", new JSONObject());
    } catch (JSONException e) {
        e.printStackTrace();
    }

    JsonObjectRequest jsonObjReq = new JsonObjectRequest(
            Request.Method.POST, url, jsonObject,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    Log.d(TAG, response.toString());
                }
            }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            // As of f605da3 the following should work
            NetworkResponse response = error.networkResponse;
            if (error instanceof ServerError && response != null) {
                try {
                    String res = new String(response.data,
                            HttpHeaderParser.parseCharset(response.headers, "utf-8"));
                    // Now you can use any deserializer to make sense of data
                    JSONObject obj = new JSONObject(res);
                } catch (UnsupportedEncodingException e1) {
                    // Couldn't properly decode data to string
                    e1.printStackTrace();
                } catch (JSONException e2) {
                    // returned data is not JSONObject?
                    e2.printStackTrace();
                }
            }
        }
    }) {
        @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;
        }
    };

    Singleton.getInstance(this).addToRequestQueue(jsonObjReq);

错误:

  

E / Volley:[275] BasicNetwork.performRequest:http://10.0.2.2:8080/order的意外响应代码400

在第二篇文章中,我发现了“内容类型”的提示,但没有任何改变。

之前我使用Postman添加了对象,如下所示:

{     “waiterId”:3,     “tableNumber”:3,     “评论”:“orderRemark”,     “产品”:[] }

有什么问题?也许我严重添加“产品”。如何在没有“产品”的情况下添加多个“产品”或发布json?

谢谢!

编辑: 我尝试将JSONObject更改为jsonObject = new JSONObject(“{\”waiterId \“:3,\”tableNumber \“:3,\”remark \“:\”orderRemark \“,\”products \“:[]}” );.现在我没有代码400问题。它只是没有发布新元素。它没有显示任何错误消息:&lt; (两个代码)

编辑2: 我尝试过其他方法。它也不起作用。

class AsyncT extends AsyncTask<Void,Void,Void> {

@Override
protected Void doInBackground(Void... params) {

    try {
        Log.d("A","1");
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("waiterId", 1);
            Log.d("A","2");
            jsonObject.put("tableNumber", 1);
            jsonObject.put("remark", "zamowienie");
            jsonObject.put("products", new JSONObject());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        URL url = new URL("http://10.0.2.2:8080/order"); 
        URLConnection urlConn;
        DataOutputStream printout;
        DataInputStream input;
        urlConn = url.openConnection();
        urlConn.setDoInput (true);
        urlConn.setDoOutput (true);
        urlConn.setUseCaches (false);
        urlConn.setRequestProperty("Content-Type","application/json");
        urlConn.setRequestProperty("Host", "android.schoolportal.gr");
        urlConn.connect();

        printout = new DataOutputStream(urlConn.getOutputStream ());
        printout.writeBytes(URLEncoder.encode(jsonObject.toString(),"UTF-8"));
        printout.flush ();
        printout.close ();

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}

1 个答案:

答案 0 :(得分:0)

使用simplified coding示例,它可以正常使用