반응형
반응형

 

package com.company.aa.indexing;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

public class test {

	public static void main(String[] args) throws IOException {

		
		// ------------------------1. 텍스트 파일을 한글자씩 읽어 리턴 ---------------------

		FileReader reader = new FileReader("D:\\file.txt");
		int ch;
		while ((ch = reader.read()) != -1) {
			System.out.print((char) ch);
		}
		
		// ------------------------2. 텍스트 파일을 한 줄씩 읽어서 리턴 ---------------------
		// 인코딩 지정 가능 
		// BufferedReader reader2 = new BufferedReader(new FileReader("d:\\file.txt", Charset.forName("UTF-8")));
		BufferedReader reader2 = new BufferedReader(new FileReader("d:\\file.txt"));
		String str;
		while ((str = reader2.readLine()) != null) {
			System.out.println(str);
		}
		reader2.close();
		
		// ------------------------3. File 클래스 이용 ---------------------
		
		List<String> lines = Files.readAllLines(Paths.get("d:\\file.txt"));
		System.out.println(lines);
		
		// ------------------------3-1. File 클래스 이용 ---------------------
		byte[] bytes = Files.readAllBytes(Paths.get("d:\\file.txt"));
		System.out.println(new String(bytes));
		
		// ------------------------3-2. File 클래스 이용 ---------------------
		String str2 = Files.readString(Paths.get("d:\\file.txt"));
		System.out.println(str2);
		
	}

}
반응형
반응형
package com.lsj.chatting;

import org.json.JSONArray;
import org.json.JSONObject;

public class testing {

	public static void main(String[] args) {


		/** JSONObject (no data) **/
		JSONObject json = new JSONObject();
		
		System.out.println("jsonFormat : " + json);
		
		/** 이름 넣기 **/
		json.put("name", "Lee");
		
		System.out.println("jsonName : " + json);
		System.out.println("name : " + json.getString("name"));
		
		/** JSONArray (취미) **/
		JSONArray hobbies = new JSONArray();

		hobbies.put("soccer");
		hobbies.put("basket ball");
		json.put("hobbies", hobbies);
		
		System.out.println("jsonNameHobbies : " + json);
		System.out.println("jsonHobbies : " + json.getJSONArray("hobbies"));

		
		/** 취미 + 이름 데이터 배열에 입력 **/
		JSONArray people = new JSONArray();
		people.put(json);
		
		/** 키에 해당하는 값이 어떤 타입이냐에 따라 get 뒤에 붙는게 정해진다. **/

		/** 이름 넣기 **/
		json = new JSONObject(); // 초기화
		json.put("name", "Tom");
		

		/** JSONArray (취미) **/
		hobbies = new JSONArray(); // 초기화
		hobbies.put("painting");
		hobbies.put("weight training");
		json.put("hobbies", hobbies);
		
		people.put(json);
		
		System.out.println("people : " + people);
		
		/** 최종 JSON **/
		JSONObject person = new JSONObject();
		person.put("members", people);

		System.out.println("person : " + person);
		
		/** 사람 출력 **/
		JSONArray members = person.getJSONArray("members");
		JSONObject member0 = members.getJSONObject(0);
		JSONObject member1 = members.getJSONObject(1);
		
		System.out.println("member0 : " + member0);
		System.out.println("member1 : " + member1);
		
		/** 취미 출력 **/
		JSONArray member0Hobbies = member0.getJSONArray("hobbies");
		System.out.println("member0Hobbies : " + member0Hobbies);
		
		String member0Hobbie = member0Hobbies.getString(0);
		System.out.println("member0Hobbie : " + member0Hobbie);
		
		member0Hobbie = (String) member0Hobbies.get(1);
		System.out.println("member0Hobbie : " + member0Hobbie);
		// person : {"members":[{"hobbies":["soccer","basket ball"],"name":"Lee"},{"hobbies":["painting","weight training"],"name":"Tom"}]}
        // 일반적 JSON 구조
	}
	
}
반응형
반응형

📝body 데이터 받기 (Servlet)

@RequestMapping(value = "/post.do", method = RequestMethod.POST)
public void post(HttpServletRequest request, HttpServletResponse response) throws IOException {
	
    // 한번만 호출 가능 (분석 안 해서 왜 그런지는 모름)
	String body = getBody(request);
    System.out.println(body);
    JSONObject obj = new JSONObject(body);

    System.out.println(obj.get("searchWord"));
    System.out.println(obj.get("pageNum"));

    response.setContentType("application/json; charset=UTF-8");
    PrintWriter writer = null;

    writer = response.getWriter();
    writer.print(obj);
    writer.flush();
}

public static String getBody(HttpServletRequest request) throws IOException {

    String body = null;
    StringBuilder stringBuilder = new StringBuilder();
    BufferedReader bufferedReader = null;

    try {
        InputStream inputStream = request.getInputStream();
        if (inputStream != null) {
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
            char[] charBuffer = new char[128];
            int bytesRead = -1;
            while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
                stringBuilder.append(charBuffer, 0, bytesRead);
            }
        }
    } catch (IOException ex) {
        throw ex;
    } finally {
        if (bufferedReader != null) {
            try {
                bufferedReader.close();
            } catch (IOException ex) {
                throw ex;
            }
        }
    }

    body = stringBuilder.toString();
    return body;
}

출처 : https://kwonyang.tistory.com/2

 

📝body 데이터 받기 (requestBody) [HashMap]

package com.lsj.spring_study;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {
	final static Logger logger = LogManager.getLogger(HomeController.class);
	final static Logger APIParamLogger = LogManager.getLogger("AS_API_PARAM");
	
	@RequestMapping(value = "/getLogs.do", method = RequestMethod.GET)
	public void logs() {

		
		APIParamLogger.error("TRACE TEST");
        logger.info("INFO TEST");
        logger.debug("DEBUG TEST");
        logger.warn("WARN TEST");
        logger.error("ERROR TEST");
        logger.fatal("FATAL TEST");
        System.out.println(logger.getLevel());
        System.out.println(logger.getLevel().intLevel());		
//		Logger APIParamLogger = LogManager.getLogger("AS_API_PARAM");
//		APIParamLogger.info("abc");
		
		
	}
	
	
	/** params **/
	@RequestMapping(value = "/params.do", method = RequestMethod.POST)
	public void params(String code,String name) {

		// 호출 Url      : localhost:8080/jsonToObject.do?name=hello&age=20e
		// Content-Type : params
		// Header 		:  key → name, Value → hello 
		// Header 		:  key → age, Value → 20
		
		System.out.println(">>> " + code); // null
		System.out.println(">>> " + name); // Lee
		
		/** 일반적으로 POST 방식에 쿼리스트링을 붙히지 않지만 붙혀도 인식이 가능하다. **/
	}

	/** params **/
	@RequestMapping(value = "/paramsToObject.do", method = RequestMethod.POST)
	public void paramsToObject(BodyVO bodyVO) {

		// 호출 Url      : localhost:8080/jsonToObject.do?name=hello&age=20e
		// Content-Type : params
		// Header 		:  key → name, Value → hello 
		// Header 		:  key → age, Value → 20
		
		System.out.println(">>> " + bodyVO.getName()); // hello
		System.out.println(">>> " + bodyVO.getAge()); // 20
		
		/** 일반적으로 POST 방식에 쿼리스트링을 붙히지 않지만 붙혀도 인식이 가능하다. **/
	}
	

	
	
	/** application/x-www-form-urlencoded **/
	@RequestMapping(value = "/urlencoded.do", method = RequestMethod.POST)
	public void urlencoded(String code,String name) {

		// 호출 Url      : urlencoded.do?name=Lee
		// Content-Type : application/x-www-form-urlencoded
		// Body 		:  key → code, Value → ABC 
		//    			   key → name, Value → Lee
		
		System.out.println(">>> " + code); // ABC
		System.out.println(">>> " + name); // Lee 
		
		// 일반적으로 POST 방식에 쿼리스트링을 붙히지 않지만 붙혀도 인식이 가능함
		// x-www-form-urlencoded 의 경우 쿼리스트링처럼 code=ABC 인식을 한다.
	}
	
	/** application/x-www-form-urlencoded **/
	@RequestMapping(value = "/urlencodedToObject.do", method = RequestMethod.POST)
	public void urlencodedToObject(BodyVO bodyVO) {
		
		// 호출 Url      : urlencoded.do
		// Content-Type : application/x-www-form-urlencoded
		//    			   key → name, Value → Lee
		// Body 		:  key → age, Value → 20 
		
		System.out.println(">>> " + bodyVO.getName()); // Lee
		System.out.println(">>> " + bodyVO.getAge()); // 20
	}
	
	/** application/x-www-form-urlencoded의 경우 따로 RequestBody가 필요없다. 동작방식이 GET의 Header와 동일한 것 같다 **/
	
	
	/** 이 밑에의 MIME 타입은 반드시 RquestBody를 사용해서 값을 받을 수 있다. **/
	/** text **/
	@RequestMapping(value = "/text.do", method = RequestMethod.POST)
	public void text(@RequestBody String bodyContents) {

		// 호출 Url      : text.do
		// body 		: this is text
		// Content-Type : text 또는 text/html
		System.out.println(">>> " + bodyContents); // this is text
		
	}
	
	
	/** application/json **/
	@RequestMapping(value = "/json.do", method = RequestMethod.POST)
	public void json(@RequestBody String bodyContents) {

		// 호출 Url      : json.do
		// body 		: {"content" : "this is json"}
		// Content-Type : application/json
		System.out.println(">>> " + bodyContents); // {"content" : "this is json"}
		
	}
	
	/** application/json (Object Injection) **/
	@RequestMapping(value = "/jsonToHashMap.do", method = RequestMethod.POST)
	public @ResponseBody HashMap<String, Object> jsonToObject(@RequestBody HashMap<String, Object> bodyVO) {

		/** BodyVO (HashMap도 또한 Object이기 떄문에 동일하게 적용 된다. **/
		// String name
		// String age → int 형으로 값을 보내면 못 자동 Injection이 안 된다. "age" : 20 (X)
		
		/** 참고로 BodyVO에 default값이 설정되어 있어도 ReuqestBody에 넘어온 값이 없다면(body에 json을 안 보내면) null로 덮어씌워진다. **/
		/** 필요사항에서는 데이터를 까서 검증하는 작업을 직접해야할 거 같다. **/
		
		// 호출 Url      : jsonToObject.do
		// body 		: {"name" : "lee", "age":"20"}
		// Content-Type : application/json
		
		System.out.println(bodyVO); // {name=lee, age=20}
		
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("bodyVO", bodyVO);
		
		return map;
	}
	
	
	/** application/json (Object Injection) **/
	@RequestMapping(value = "/jsonToObject.do", method = RequestMethod.POST)
	public @ResponseBody HashMap<String, Object> jsonToObject(@RequestBody BodyVO bodyVO) {

		/** BodyVO (HashMap도 또한 Object이기 떄문에 동일하게 적용 된다. **/
		// String name
		// String age → int 형으로 값을 보내면 못 자동 Injection이 안 된다. "age" : 20 (X)
		
		/** 참고로 BodyVO에 default값이 설정되어 있어도 ReuqestBody에 넘어온 값이 없다면(body에 json을 안 보내면) null로 덮어씌워진다. **/
		/** 필요사항에서는 데이터를 까서 검증하는 작업을 직접해야할 거 같다. **/
		
		// 호출 Url      : jsonToObject.do
		// body 		: {"name" : "lee", "age":"20"}
		// Content-Type : application/json
		System.out.println(">>> " + bodyVO.getName()); // lee
		System.out.println(">>> " + bodyVO.getAge()); // 20
		
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("bodyVO", bodyVO);
		
		return map;
	}
	
	/**
	 * jsonToObject.do을 사용하기 위해서는 하기 라이브러리가 필요 (body 내용을 Object에 Injeciton)
	 * 없어도 주입이 되는 것처럼 보이지만 4번에 한번씩 에러를 뱉는 현상 발견
	<dependency>
		<groupId>com.fasterxml.jackson.core</groupId>
		<artifactId>jackson-databind</artifactId>
		<version>2.9.3</version>
	</dependency>
	
	<dependency>
		<groupId>org.codehaus.jackson</groupId>
		<artifactId>jackson-mapper-asl</artifactId>
		<version>1.9.13</version>
	</dependency>
	**/
	
	
	
	
	
	
	
	/** responseBody란 처리한 결과를 클라이언트에게 다시 돌려줘서 읽을 수 있게한다. (즉 return 값이 있어야한다.) **/
	// 미사용시 → 404 페이지를 찾을 수 없음
	// 사용시 → {"bodyVO" : {"name" : "lee", "age":"20"}}
	

}
  • RequestBody를 이용해 body에 내용을 읽을 수 있다.
  • 주의) 라이브러리 필요  → 전자정부의 경우 dispatcher에 추가 작업 해야함 

 

<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.13</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.3</version>
</dependency>

 

📝POST방식 통신 (return JSONObject)

StringBuffer response;
// map은 body에 담아서 보낼 데이터가 존재할 때 사용 (일반적 json으로 많이 보내서 적음)
public JSONObject getConnection(String uri, HashMap<String,Object> map) {
    StringBuilder sb = null;

    HttpURLConnection conn = null;
    JSONObject responseJson = null;

    try {
        URL url = new URL(uri);

        conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5000);
        conn.setReadTimeout(5000);
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-Type", "application/json");



        System.out.println(map);
/*			
        // body에 json 데이터 담아서 request 할때 사용
        JSONObject obj = new JSONObject(map);

        try (OutputStream os = conn.getOutputStream()){
            byte request_data[] = obj.toString().getBytes("utf-8");
            os.write(request_data);
            os.close();
        }			
*/

        int responseCode = conn.getResponseCode();
        if (responseCode == 400 || responseCode == 401 || responseCode == 500) {
            System.out.println(responseCode + " Error!");
        } else {
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
            sb = new StringBuilder();
            String line = "";
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            responseJson = new JSONObject(sb.toString());
            // System.out.println(responseJson);

            return responseJson;
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        System.out.println("not JSON Format response");
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return responseJson;
}

 

 

📝Get방식 통신 (return JSONObject)

public JSONObject getConnection(String uri) {
    StringBuilder sb = null;

    HttpURLConnection conn = null;
    JSONObject responseJson = null;

    try {
        URL url = new URL(uri);

        conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5000);
        conn.setReadTimeout(5000);
        conn.setRequestMethod("GET");
        // conn.setDoOutput(true);

        JSONObject commands = new JSONObject();

        int responseCode = conn.getResponseCode();
        if (responseCode == 400 || responseCode == 401 || responseCode == 500) {
            System.out.println(responseCode + " Error!");
        } else {
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
            sb = new StringBuilder();
            String line = "";
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            responseJson = new JSONObject(sb.toString());
            // System.out.println(responseJson);

            return responseJson;
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        System.out.println("not JSON Format response");
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return responseJson;
}

 

📝Get방식 통신 (return String)

StringBuffer response;
public String callGetMethod(String url) {		


    try {

        // 통신 주소  등록
        URL obj = new URL(url);

        // 통신 방식 설정
        HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
        conn.setRequestProperty("Content-Type", "application/json; charset=utf-8" );
        conn.setDoOutput(true);
        conn.setRequestMethod("GET");

        // ---- 읽어온 데이터를 담기 ----
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));

        String inputLine;
        response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

    } catch (Exception e) {
        e.printStackTrace();
    }

    // ---- 읽어온 데이터를 반환 ----
    String responseData =response.toString();
    return responseData; 
}

conn.setRequestProperty만 주의해서 작성 나머진 그대로 활용 가능 → application/json; charset-utf-8

 

📝Delete 방식 통신

public void callDeleteMethod(String url) {

    URL obj;
    try {
        obj = new URL(url);

        HttpURLConnection httpCon = (HttpURLConnection) obj.openConnection();
        httpCon.setDoOutput(true);
        httpCon.setRequestMethod("DELETE");
        httpCon.connect();

        int responseCode = httpCon.getResponseCode();
        // connect만 해서 끝이 아니라 무조건 어떤 행동을 해야 위에 동작이 진행된다.

    } catch (Exception e) {
        e.printStackTrace();
    }
}
반응형
반응형
String encodeResult = URLEncoder.encode(String encodingString, String charsetName);
String decodeResult = URLDecoder.decode(String decodingString, String charsetName);

예) 
  String encodeResult = URLEncoder.encode("짜장면", "UTF-8");
  String encodeResult = URLEncoder.encode("짜장면", "EUC-KR");
  String decodeResult = URLDecoder.decode("라면","UTF-8");

이런식으로 사용 가능합니다. 

 

반응형