API 와 JSON 추가

This commit is contained in:
daniel LEE 2023-10-24 17:12:15 +09:00
parent b9616eae65
commit 225723fe48
4 changed files with 365 additions and 6 deletions

17
pom.xml
View File

@ -17,6 +17,23 @@
<dependencies> <dependencies>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20160810</version>
</dependency>
<!--<scope>provided</scope> provided로 지정하면 패키징시 제외됩니다. -->
<dependency> <dependency>
<groupId>org.apache.tomcat.embed</groupId> <groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId> <artifactId>tomcat-embed-jasper</artifactId>

View File

@ -0,0 +1,207 @@
package com.example.demo.config;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Iterator;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import com.google.gson.Gson;
public class HttpUtil {
public static void sendGet(String url) {
try {
URL u = new URL(url);
HttpURLConnection httpCon = (HttpURLConnection) u.openConnection();
// httpCon.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// httpCon.setDoOutput(true);
// httpCon.setDoInput(true);
httpCon.setRequestMethod("GET");
InputStream in = new BufferedInputStream(httpCon.getInputStream());
String result = org.apache.commons.io.IOUtils.toString(in, "UTF-8");
System.out.println(result);
in.close();
httpCon.disconnect();
} catch(Exception e) {
e.printStackTrace();
}
}
/**
* 객체를 JSON 문자열로 POST 방식으로 전송한다.
* @param url
* @param object
*/
public static void sendObject2Json(String url, Object object) {
try {
URL u = new URL(url);
HttpURLConnection httpCon = (HttpURLConnection) u.openConnection();
httpCon.setRequestProperty("Content-Type", "application/json; charset=EUC-KR");
httpCon.setDoOutput(true);
httpCon.setDoInput(true);
httpCon.setRequestMethod("POST");
OutputStream raw = httpCon.getOutputStream();
//OutputStream buffered = new BufferedOutputStream(raw);
//OutputStreamWriter out = new OutputStreamWriter(buffered,"UTF-8");
//OutputStreamWriter out = new OutputStreamWriter(buffered);
//Object -> JSON
String jsonStr = new Gson().toJson(object);
System.out.println("ready to send : " + url);
System.out.println("converted json data: \n" + jsonStr);
//전송
raw.write(jsonStr.getBytes("EUC-KR"));
raw.flush();
raw.close();
// read the response
System.out.println(httpCon.getResponseCode());
System.out.println(httpCon.getResponseMessage());
InputStream in = new BufferedInputStream(httpCon.getInputStream());
String result = org.apache.commons.io.IOUtils.toString(in, "UTF-8");
System.out.println(result);
in.close();
httpCon.disconnect();
} catch(Exception e) {
e.printStackTrace();
}
}
/**
* 객체를 GET 파라미터 형식의 POST 방식으로 전송한다.
* @param url
* @param object
*/
public static void sendObject2Post(String url, Object object) {
try {
URL u = new URL(url);
HttpURLConnection httpCon = (HttpURLConnection) u.openConnection();
httpCon.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpCon.setDoOutput(true);
httpCon.setDoInput(true);
httpCon.setRequestMethod("POST");
OutputStream raw = httpCon.getOutputStream();
//OutputStream buffered = new BufferedOutputStream(raw);
//OutputStreamWriter out = new OutputStreamWriter(buffered,"UTF-8");
//OutputStreamWriter out = new OutputStreamWriter(buffered);
//Object -> JSON
String jsonStr = new Gson().toJson(object);
System.out.println("ready to send : " + url);
System.out.println("converted json data: \n" + jsonStr);
StringBuilder sb = new StringBuilder();
JSONObject json = new JSONObject(jsonStr);
Iterator<String> keys = json.keys();
//sb.append("?"); //start of query args
while (keys.hasNext()) {
String key = keys.next();
sb.append(key);
sb.append("=");
sb.append( URLEncoder.encode((String)json.get(key), "EUC-KR") );
sb.append("&"); //To allow for another argument.
}
String queryStr = sb.toString();
System.out.println( "json to query :" + queryStr );
//전송
raw.write(queryStr.getBytes("EUC-KR"));
raw.flush();
raw.close();
// read the response
System.out.println(httpCon.getResponseCode());
System.out.println(httpCon.getResponseMessage());
InputStream in = new BufferedInputStream(httpCon.getInputStream());
String result = org.apache.commons.io.IOUtils.toString(in, "UTF-8");
System.out.println(result);
in.close();
httpCon.disconnect();
} catch(Exception e) {
e.printStackTrace();
}
}
/**
* 객체를 GET 파라미터 형식의 POST 방식으로 전송한다.
* @param url
* @param object
*/
public static void send2PostOrderId(String url, String moduleId, String orderId, String userId) {
try {
URL u = new URL(url);
HttpURLConnection httpCon = (HttpURLConnection) u.openConnection();
httpCon.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpCon.setDoOutput(true);
httpCon.setDoInput(true);
httpCon.setRequestMethod("POST");
OutputStream raw = httpCon.getOutputStream();
System.out.println("ready to send : " + url);
String queryStr = "moduleId=" + moduleId + "&" + "orderId=" + orderId + "&" + "userId=" + userId;
System.out.println( "json to query :" + queryStr );
//전송
raw.write(queryStr.getBytes("EUC-KR"));
raw.flush();
raw.close();
// read the response
System.out.println(httpCon.getResponseCode());
System.out.println(httpCon.getResponseMessage());
InputStream in = new BufferedInputStream(httpCon.getInputStream());
String result = org.apache.commons.io.IOUtils.toString(in, "UTF-8");
System.out.println(result);
in.close();
httpCon.disconnect();
} catch(Exception e) {
e.printStackTrace();
}
}
/** 클라이언트 ip 추출
PROXY SERVER 또는 LOAD BALANCER를 거치는 경우 ip가 접속하기 직전의 ip로 들어오게 된다.
PROXY SERVER 또는 LOAD BALANCER를 거칠 경우 reuqest header의 HTTP_X_FORWARDED_FOR 키워드에 정보를 남김으로
먼저 확인 없을 경우 request.getRemoteAddr() ip를 추출한다. */
public static String getClientIp(HttpServletRequest request) throws Exception {
String ip = request.getHeader("HTTP_X_FORWARDED_FOR");
if ( StringUtils.isEmpty( ip ) ) {
ip = request.getRemoteAddr();
}
return ip;
}
}//end class

View File

@ -1,5 +1,19 @@
package com.example.demo.controller; package com.example.demo.controller;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.ui.Model; import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
@ -7,11 +21,113 @@ import org.springframework.web.bind.annotation.GetMapping;
@Controller @Controller
public class JSPController { public class JSPController {
@GetMapping("/hello") // @Value("${openApi.serviceKey}")
// private String serviceKey;
//
// @Value("${openApi.callBackUrl}")
// private String callBackUrl;
//
// @Value("${openApi.dataType}")
// private String dataType;
@GetMapping("/list")
public String home(Model model) { public String home(Model model) {
System.out.println("home controller start");
model.addAttribute("name", "111111."); model.addAttribute("start", "start....OK");
ResponseEntity<String> result = callForecastApi();
// System.out.println(result);
JSONObject json = new JSONObject(result);
model.addAttribute("name", result);
JSONArray jsonArr = new JSONArray( json.get("body").toString() );
// System.out.println( jsonArr );
List<Object> list = new ArrayList<Object>();
for ( int i = 0; i < jsonArr.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject obj = jsonArr.getJSONObject(i);
map.put( "id", obj.getString("phone") );
map.put( "name", obj.getString("name") );
map.put( "phone", obj.getString("phone") );
map.put( "address", obj.getString("phone") );
map.put( "filepath", obj.getString("filepath") );
list.add(map);
}
model.addAttribute("list", list);
return "hello"; return "hello";
} }
// public ResponseEntity<String> callForecastApi(
// @RequestParam(value="base_time") String baseTime,
// @RequestParam(value="base_date") String baseDate,
// @RequestParam(value="beach_num") String beachNum ) {
public ResponseEntity<String> callForecastApi() {
HttpURLConnection urlConnection = null;
InputStream stream = null;
String result = null;
// String urlStr = callBackUrl +
// "serviceKey=" + serviceKey +
// "&dataType=" + dataType +
// "&base_date=" + baseDate +
// "&base_time=" + baseTime +
// "&beach_num=" + beachNum;
String urlStr = "https://api.leejk0523.com/profile/user/all";
try {
URL url = new URL(urlStr);
urlConnection = (HttpURLConnection) url.openConnection();
stream = getNetworkConnection(urlConnection);
result = readStreamToString(stream);
if (stream != null) stream.close();
} catch(IOException e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return new ResponseEntity<>(result, HttpStatus.OK);
}
/* URLConnection 을 전달받아 연결정보 설정 후 연결, 연결 후 수신한 InputStream 반환 */
private InputStream getNetworkConnection(HttpURLConnection urlConnection) throws IOException {
urlConnection.setConnectTimeout(3000);
urlConnection.setReadTimeout(3000);
urlConnection.setRequestMethod("GET");
urlConnection.setDoInput(true);
if(urlConnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new IOException("HTTP error code : " + urlConnection.getResponseCode());
}
return urlConnection.getInputStream();
}
/* InputStream을 전달받아 문자열로 변환 후 반환 */
private String readStreamToString(InputStream stream) throws IOException{
StringBuilder result = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
String readLine;
while((readLine = br.readLine()) != null) {
result.append(readLine + "\n\r");
}
br.close();
return result.toString();
}
} }

View File

@ -7,6 +7,25 @@
<title>Insert title here</title> <title>Insert title here</title>
</head> </head>
<body> <body>
${ name }
${ start } <br><br><br>
전체보기 <br>
${ name } <br><br><br>
<c:forEach items="${list}" var="profile">
<table border="1" bordercolor="blue" width ="50%" height="100">
<thead>
<tr align = "center" >
<td><c:out value="${profile.id}" /></td>
<td><c:out value="${profile.name}" /></td>
<td><c:out value="${ profile.phone}" /></td>
<td><c:out value="${ profile.address}" /></td>
<td><c:out value="${ profile.filepath}" /><br></td>
</tr>
</thead>
</table>
</c:forEach>
</body> </body>
</html> </html>