【发布时间】: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