Remark : 웹서버에 Json 보내고 Json으로 받아서 PrettyPrint 로 저장해보자.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
package com.example.demo; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.google.gson.JsonParser; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import java.io.*; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; @SpringBootApplication public class DemoApplication { public static void main(String[] args) throws IOException { SpringApplication.run(DemoApplication.class, args); String host_url = "http://dev.our.com:8099/dev/Far/v1.00"; HttpURLConnection conn = null; try { JSONObject RetVal = Res.RqModel(); //만든 Json 리턴 함수 URL url = new URL(host_url); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setDoOutput(true); BufferedWriter bw = new BufferedWriter((new OutputStreamWriter(conn.getOutputStream()))); bw.write(RetVal.toString()); //data bw.flush(); bw.close(); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String returnMsg = in.readLine(); //JSONParser parser = new JSONParser(); //JSONObject jsonObject = (JSONObject) parser.parse(returnMsg); //ModelVo modelVo = new Gson().fromJson(returnMsg, ModelVo .class); // PrettyPrint Gson gson = new GsonBuilder().setPrettyPrinting().create(); JsonElement je = JsonParser.parseString(returnMsg); String prettyJsonString = gson.toJson(je); try (PrintWriter out = new PrintWriter("Res.json")) { out.println(prettyJsonString); } //System.out.println("응답메시지:" + returnMsg); int responseCode = conn.getResponseCode(); if (responseCode == 400) { System.out.println("400:명령 실행 오류"); } else if (responseCode == 500) { System.out.println(responseCode + " : 응답코드임"); } } catch (FileNotFoundException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); //} catch (ParseException e) { // throw new RuntimeException(e); } } } |