【问题标题】:Sending JSON's through HTTP Request, but the Response is NULL通过 HTTP 请求发送 JSON,但响应为 NULL
【发布时间】:2019-11-20 07:23:04
【问题描述】:

我需要将一些 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 应用程序,它在控制器中等待“POST”请求并将 JSON 的内容发送到数据库。

【问题讨论】:

  • 将JsonObject转为字节数组

标签: java json post httprequest outputstream


【解决方案1】:

它对我有用。 使用 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();
    }

  }
}

【讨论】:

  • 感谢您的回答,我发现问题是我的“发送”模型与“接收”应用程序的模型的参数名称不同。
  • 您有什么想法我怎样才能实现此代码以更快地发送?
  • 如果你使用的是spring,那么使用rest模板。RestTemplete 速度很快,我们可以很容易地实现,它返回可以理解的错误代码。否则,只使用这个。如果可能,建议我一次发送数据列表。
【解决方案2】:

将JsonObject转成字节数组再写入

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

输出流 os = con.getOutputStream(); os.write(outputBytes);

【讨论】:

  • 我用你的变体替换了我的操作系统,但我仍然得到一个 NULL 响应。这是来自“接收者”应用程序的错误:“java.sql.BatchUpdateException:批处理条目 0 插入到员工(employeeId,employeeName)值(NULL,NULL)被中止:错误:“employeeid”列中的空值违反了不 -空约束”
猜你喜欢
  • 2020-07-08
  • 2013-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多