package com.mytestt.URLConnection;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* Handles requests for the application home page.
*/
@Controller
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
/**
* Simply selects the home view to render by returning its name.
*/
@RequestMapping(value = "/", method = RequestMethod.GET) public String
home(Locale locale, Model model) {
logger.info("Welcome home! The client locale is {}.", locale);
Date date = new Date(); DateFormat dateFormat =
DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
String formattedDate = dateFormat.format(date);
model.addAttribute("serverTime", formattedDate );
return "home"; }
@RequestMapping(value="/test")
@ResponseBody
public List<Map<String, Object>> responseBodyTest(@RequestParam Map<String, Object> params, HttpServletRequest request){
List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
String testStr="";
String param = "{title: 'foo', body: 'bar', userId: 1}";
try {
testStr = httpURLConnection("https://jsonplaceholder.typicode.com/posts",param);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("testStr::::::" + testStr );
return result;
}
public String httpConnection(String targetUrl) {
URL url = null;
HttpURLConnection conn = null;
String jsonData = "";
BufferedReader br = null;
StringBuffer sb = null;
String returnText = "";
try {
url = new URL(targetUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Accept", "application/json");
conn.setRequestMethod("POST");
conn.connect();
br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
sb = new StringBuffer();
while ((jsonData = br.readLine()) != null) {
sb.append(jsonData);
}
returnText = sb.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null) br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return returnText;
}
/**
* 요청URL을 받아 통신하기
* @param returnUrl
* @return 응답결과
* @throws Exception
*/
public String httpURLConnection(String returnUrl, String parameterInfo) throws IOException {
StringBuffer retStr = new StringBuffer();
OutputStream os = null;
BufferedWriter writer = null;
BufferedReader br = null;
try {
URL url = new URL(returnUrl);
HttpURLConnection huc = (HttpURLConnection) url.openConnection();
huc.setRequestMethod("POST");
huc.setDoInput(true);
huc.setDoOutput(true);
huc.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
huc.setConnectTimeout(2000); //상대방 서버 통신 오류로 인해 접속 지연시 강제로 timeout 처리;
huc.setReadTimeout(2000); //상대방 서버 통신 오류로 인해 접속 지연시 강제로 timeout 처리;
os = huc.getOutputStream();
writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(parameterInfo);
writer.flush(); // 버퍼를 비워준다.
// 응답받은 메시지의 길이만큼 버퍼를 생성하여 읽어들임
br = new BufferedReader(new InputStreamReader(huc.getInputStream(), "UTF-8"));
String data;
// 표준출력으로 한 라인씩 출력
data = br.readLine();
while(data != null ) {
if(retStr.length() > 0) {
retStr.append("\n");
}
retStr.append(data);
data = br.readLine();
}
} catch (Exception e) {
throw new IOException("요청URL을 받아 통신 처리하는 도중 예기치 않은 오류 발생", e);
} finally{
// 스트림을 닫는다.
try {
if(os != null){
os.close();
}
}catch(IOException e) {
new IOException("OutputStream close 처리 도중 예기치 않은 오류 발생", e);
}
try {
if(writer != null){
writer.close();
}
}catch(IOException e) {
new IOException("BufferedWriter close 처리 도중 예기치 않은 오류 발생", e);
}
try {
if(br != null){
br.close();
}
}catch(IOException e) {
new IOException("BufferedReader close 처리 도중 예기치 않은 오류 발생", e);
}
}
return retStr.toString();
}
public static void main(String[] args) throws Exception {
URL url = new URL("http://www.example.net/test.php"); // 호출할 url
Map<String,Object> params = new LinkedHashMap<>(); // 파라미터 세팅
params.put("name", "james");
params.put("email", "james@example.com");
params.put("reply_to_thread", 10394);
params.put("message", "Hello World");
StringBuilder postData = new StringBuilder();
for(Map.Entry<String,Object> param : params.entrySet()) {
if(postData.length() != 0) postData.append('&');
postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
conn.setDoOutput(true);
conn.getOutputStream().write(postDataBytes); // POST 호출
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String inputLine;
while((inputLine = in.readLine()) != null) { // response 출력
System.out.println(inputLine);
}
in.close();
}
}
}
'2019백업' 카테고리의 다른 글
코드블럭 테스트 (0) | 2019.12.25 |
---|---|
Javascript-classList (0) | 2019.07.26 |
JavaScript - Variable (0) | 2019.07.26 |
JavaScript - 노드복제와 템플릿 태그 (0) | 2019.07.24 |
JavaScript - 노드조작: 메뉴추가 (0) | 2019.07.24 |