Search code examples
javajsoneclipsepostform-data

How to get proper response when posting form data to php server using eclipse?


I am posting json data to the server but on getting the response it should be like this

 {"id":65,"check":1,"date":"08-Jan-19"}

instead, I am getting this

{"id":"65check=1","check":null,"date":"08-Jan-19"}

This is the code on button click I send json form data to the server but in response, the id value gets attached to check value, how to get the proper response.

Attendance_TimeCheck = "1";
        users_identify = "65";
        try {
           URL urlForPostRequest = new URL("http://xenzet.com/ds/getrec.php");

            System.out.println("Instantiated new URL: " + urlForPostRequest);
            final long id = Long.valueOf(users_identify);
            HttpURLConnection conection = (HttpURLConnection) urlForPostRequest.openConnection();
            conection.setDoOutput(true);
            conection.setRequestMethod("POST");
            conection.setRequestProperty("User-Agent", "Mozilla/5.0");
            conection.getOutputStream().write(("id="+id).getBytes(StandardCharsets.UTF_8));
            conection.getOutputStream().write(("check="+Attendance_TimeCheck).getBytes(StandardCharsets.UTF_8));
            conection.connect();

            BufferedInputStream bis = new BufferedInputStream(conection.getInputStream());
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            int resultBuffer = bis.read();
            while (resultBuffer != -1) {
                bos.write((byte) resultBuffer);
                resultBuffer = bis.read();
            }
            String result1 = bos.toString();
            System.out.println(result1);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

I think the string is being read wrongly.


Solution

  • Check the payload you are passing to the POST request,

    conection.getOutputStream().write(("id="+id).getBytes(StandardCharsets.UTF_8));
    conection.getOutputStream().write(("check="+Attendance_TimeCheck).getBytes(StandardCharsets.UTF_8));
    

    "id="+id followed by "check="+Attendance_TimeCheck will result to "id":"65check=1"

    append the ampersand before the queryparam check to get the desired result,

    conection.getOutputStream().write(("&check="+Attendance_TimeCheck).getBytes(StandardCharsets.UTF_8));