java - 通过 HTTP 请求发送 JSON,但响应为 NULL

标签 java json post httprequest outputstream

我需要将一些 JSON 发送到我的另一个应用程序,以便它将它们存储在数据库中。 我的问题是其他应用程序不断获取 NULL 参数。 这是我的“发送者”应用程序:

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();
        }

    }
}

“接收器应用程序是一个简单的 spring-boot 应用程序,等待 Controller 中的“POST”请求并将 JSON 的内容发送到数据库。

最佳答案

它对我有用。 使用 Gson 将 Java Dto 解析为 JSON 类型。下载com.google.code.gson.jar-2.2.4版本。 在您的代码中,我遇到了解析问题。

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();
    }

  }
}

关于java - 通过 HTTP 请求发送 JSON,但响应为 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58948827/

相关文章:

java - 以编程方式叠加图像

java - 为什么我的动画创建 java 代码在我的 android 项目中不起作用?

post - Python 错误 : Type error: POST data should be bytes; also user-agent issue

Python 通过 JSON 迭代数据

python - 带有 Python 请求的 XML POST

java - 读取 Android POST 请求的回显

java - 使用 javascript 和 java 从服务器下载文件到本地计算机

java - 如果服务器突然宕机,Java代码会中途终止吗

json - 将[][]接口(interface)转换为[][]字符串

android - 如何将base64编码的音频转换为JSON?