Cazan Bogdan
Cazan Bogdan

Reputation: 21

Sending JSON's through HTTP Request, but the Response is NULL

I need to send some JSONs to another application of mine, for it to store them in a database. My problem is that the other app keeps getting NULL parameters. Here is my "sender" app:

public class Main {

    public static void main(String[] args) {
        ConcurrentLinkedQueue<Employee> employeeQueue = new ConcurrentLinkedQueue<>();

        for (int i = 0; i <= 10; i++) {
            byte[] array = new byte[7]; // length is bounded by 7
            new Random().nextBytes(array);
            String generatedString = new String(array, Charset.forName("UTF-8"));
            long id = new Random().nextLong() & 0xffffffffL;
            employeeQueue.add(new Employee(id, generatedString));
        }


        try {
            while (!employeeQueue.isEmpty()) {
                JSONObject json = new JSONObject(employeeQueue.remove());

                URL url = new URL("http://localhost:8080/postgressApp/createEmp");
                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                con.setRequestMethod("POST");
                con.setRequestProperty("Content-Type", "application/json; utf-8");
                con.setRequestProperty("Accept", "application/json");
                con.setDoOutput(true);

                OutputStream os = con.getOutputStream();
                OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
                try {
                    json.write(osw);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                osw.flush();
                osw.close();    
                os.close();

                try (BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"))) {
                    StringBuilder response = new StringBuilder();
                    String responseLine = null;
                    while ((responseLine = br.readLine()) != null) {
                        response.append(responseLine.trim());
                    }
                    System.out.println("Response from server: " + response.toString());
                }

            }

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

    }
}

The "receiver app is a simple spring-boot app waiting for "POST" Requests in a Controller and sending the content of the JSON to a database.

Upvotes: 0

Views: 789

Answers (2)

Ranjith Bokkala
Ranjith Bokkala

Reputation: 379

It is working for me. Use Gson for parsing Java Dto to JSON type. download com.google.code.gson.jar-2.2.4 version. In your code, I got the issue with parsing.

public class Main {

public static void main(String[] args) {
    ConcurrentLinkedQueue<Employee> employeeQueue = new ConcurrentLinkedQueue<>();

    for (int i = 0; i <= 10; i++) {
        byte[] array = new byte[7]; // length is bounded by 7
        new Random().nextBytes(array);
        String generatedString = new String(array, Charset.forName("UTF-8"));
        long id = new Random().nextLong() & 0xffffffffL;
        employeeQueue.add(new Employee(id, generatedString));
    }


    try {
        while (!employeeQueue.isEmpty()) {

          Gson gson = new GsonBuilder().setPrettyPrinting().create();  


                String jsonEmp = gson.toJson(employeeQueue.remove());

          //  JSONObject json = new JSONObject(employeeQueue.remove());

            URL url = new URL("http://localhost:8080/postgressApp/createEmp");
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("POST");
            con.setRequestProperty("Content-Type", "application/json; utf-8");
            con.setRequestProperty("Accept", "application/json");
            con.setDoOutput(true);

            OutputStream os = con.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
            try {
                 osw.write(jsonEmp);
               // json.write(osw);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            osw.flush();
            osw.close();    
            os.close();

            try (BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"))) {
                StringBuilder response = new StringBuilder();
                String responseLine = null;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                }
                System.out.println("Response from server: " + response.toString());
            }

        }

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

  }
}

Upvotes: 1

vivekdubey
vivekdubey

Reputation: 510

Convert JsonObject into byte array then write

byte [] outputBytes=json.toString().getBytes("UTF-8")

OutputStream os = con.getOutputStream(); os.write(outputBytes);

Upvotes: 1

Related Questions