将Java中的简单JSON对象发送到Servlet

时间:2017-02-04 20:54:49

标签: java json servlets send

我正在尝试将JSONObject(org.json)从java客户端发送到servlet,但在我的服务器端,我为HttpServletRequest.getParameter(“Command”)或任何参数获取“null”。

在我的客户方面:

JSONObject json = new JSONObject();
    try{
        json.put("Command","spost");
        json.put("Name","pc1");
        json.put("Pwd","pc1");
        sendRequest(json);
    } catch(JSONException jsone){

    }
    URL url;
    HttpURLConnection connection = null;
    ObjectOutputStream out;
    try {
        url = new URL("http://myURL.com/myservlet");     //Creating the URL.
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        //connection.setRequestProperty("Accept", "application/json");
        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        //Send request
        OutputStream os = connection.getOutputStream();
        OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
        System.out.println(json.toString());
        osw.write(json.toString());
        osw.flush();
        osw.close();
        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            System.out.println("Ok response");
        } else {
            System.out.println("Bad response");
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }

然后在打印json.toString()时得到类似的东西:

{"Name":"pc1","Command":"SignalPost","Pwd":"pc1"}

......这看起来很正常。

我看到一个“Ok响应”并且我的servlet检测到了httprequest,但似乎有一些错误理解json对象

我的servlet对于我使用AJAX制作的另一个客户端工作正常,所以我猜问题就在这个java客户端。

你能帮帮我吗?我用谷歌搜索并尝试了一切没有运气

由于

编辑:

最后,在服务器端,此代码正在运行:

    @Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    try{
        StringBuilder sb = new StringBuilder();
        BufferedReader br = request.getReader();
        String str = null;
        while ((str = br.readLine()) != null) {
            sb.append(str);
            System.out.println(str);
        }
        JSONObject jObj = new JSONObject(sb.toString());
        String name = jObj.getString("Name");
        String pwd = jObj.getString("Pwd");
        String command = jObj.getString("Command");

        JSONObject json = new JSONObject();
        response.setContentType("application/json");
        response.setHeader("Cache-Control", "nocache");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        out.print(json.toString());
    } catch (Exception e) {
      e.printStackTrace();
    }
}

虽然我更愿意继续使用来自客户端的GET请求,这样我就不必重新编写所有的servlet端

2 个答案:

答案 0 :(得分:0)

您的json对象未作为请求参数发送,它将在请求正文中发送。

因此,在服务器端servlet中,您不必尝试从任何请求参数中恢复它,您必须从HttpServletRequest的InputStream中读取它。

读取它,然后使用您在servlet方法中选择的json库解析它,您将获得它。

答案 1 :(得分:-1)

尝试添加connection.connect()

try {
        url = new URL("http://myURL.com/myservlet");     //Creating the URL.
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        //connection.setRequestProperty("Accept", "application/json");
        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);

        connection.connect() //New line



        //Send request
        OutputStream os = connection.getOutputStream();
        OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
        System.out.println(json.toString());
        osw.write(json.toString());
        osw.flush();
        osw.close();
        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            System.out.println("Ok response");
        } else {
            System.out.println("Bad response");
        }