Overview : xml 전송 및 받기
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 |
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.StandardCharsets; public class NetSample { public static void main(String[] args) { try { // URL of the API endpoint String targetURL = "http://dev.test.co.kr/test.aspx"; // The XML data to be sent String xmlData = "<catalog>" + " <book id="bk101">\n" + " <author>Gambardella, Matthew</author>\n" + " <genre>Computer</genre>\n" + " <price>44.95</price>\n" + " </book>\n" + " <catalog>"; // Create the URL object URL url = new URL(targetURL); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // Configure the POST request connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/xml"); connection.setDoOutput(true); // Write the XML data to the request body try (OutputStream os = connection.getOutputStream()) { byte[] input = xmlData.getBytes(StandardCharsets.UTF_8); os.write(input, 0, input.length); } // Get the response code int responseCode = connection.getResponseCode(); System.out.println("POST Response Code :: " + responseCode); // Process the response if (responseCode == HttpURLConnection.HTTP_OK) { // success BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // Print the result System.out.println("Response: " + response.toString()); } else { System.out.println("POST request failed."); } } catch (Exception e) { e.printStackTrace(); } } } |