티스토리 뷰

카카오맵api를 사용해서 가맹점 정보 json데이터를 받아오려고 했는데 간단해 보였지만 꽤 많은 시련이 있었다.. ( 하루 걸림 )

 

sts4 자바 컨트롤러로 api를 호출하다 마주친 오류들과 해결법을 정리해봅시다.

 

1. 마주친 오류메세지

rest api키도 제대로 넣고 컨트롤러 매핑 경로도 그대로 작성했는데 계속 파라미터를 못찾았다. 

[java.lang.String] not specified, and parameter name information not available via reflection. Ensure that the compiler uses the '-parameters' flag.] 

 

일단 나는 다른 패키지에 @RequestMapping주소가 같은 클래스가 있어서 문제였다.

 

2. 0건 조회

일단 나의 처음 RestController 코드

@Log4j2
@RestController
@RequestMapping("/api/kakaomap")
public class KakaoMapController {
	 @Autowired
	 private KakaoMapService kakaoMapService;
	 @Autowired
    private StoreService storeService;
	 
	 @GetMapping("/search")
	 public ResponseEntity<JsonNode> searchAddress(@RequestParam("keyword") String keyword) {
	
	    //결과
	    JsonNode result = kakaoMapService.searchPlaceByKeyword(keyword);
	    if (result != null) {
	        return ResponseEntity.ok(result);
	    } else {
	        return ResponseEntity.status(500).body(null);
	    }
	 }
 }

 

서비스 클래스에서 API호출 로직을 작성 

@Log4j2
@Service
public class KakaoMapService {
	
	 	private final String KAKAO_API_KEY = "발급받은 REST API 키"; 
	    private final String KAKAO_API_URL = "https://dapi.kakao.com/v2/local/search/keyword.json";
	    
	 	public JsonNode searchPlaceByKeyword(String keyword) {
	    	 try {
	    		 	
	    	        RestTemplate restTemplate = new RestTemplate();//Rest Template 객체 생성
	    	        
                    //헤더 설정을 위해 HttpHeaders클래스 생성한 후 HttpEntity 객체에 넣어줌
	    	        HttpHeaders headers = new HttpHeaders();
	    	        headers.set("Authorization", "KakaoAK " + KAKAO_API_KEY); 

	    	        HttpEntity<String> entity = new HttpEntity<>(headers);

	    	        // URL 인코딩 
	    	        String encodedKeyword = URLEncoder.encode(keyword, StandardCharsets.UTF_8.toString());
	    	        String url = "https://dapi.kakao.com/v2/local/search/keyword.json?query=" + encodedKeyword;

	    	        // exchange()로 API 호출
	    	        ResponseEntity<JsonNode> response = restTemplate.exchange(url, HttpMethod.GET, entity, JsonNode.class);

	    	        // 결과 반환
	    	        if (response.getStatusCode().is2xxSuccessful()) {
	    	        	
	    	        	//응답 값
	    	        	JsonNode result = response.getBody();
	                   
	    	        	return result; 
	    	        } else {
	    	            System.out.println("Error: " + response.getStatusCode());
	    	            return null;
	    	        }
	    	    } catch (Exception e) {
	    	        e.printStackTrace();
	    	        return null;
	    	    }
	    	
	    }

=> 포스트맨에서는 잘 조회되는데, 개발서버에서 조회했을 때 토탈 카운트가 0건이 찍혔다.

일단 keyword에 들어간 값이 인코딩된 값인게 문제인 것 같아 디코딩을 추가해줬지만 결과는 똑같았다.

 

 

친구 swimming에게 코드를 보여줬다가 인코딩을 하는 이유가 무엇이냐는 말을 듣고 의문이었는데  그 부분만 주석을 하고 컨트롤러 매핑 주소에도 produces를 추가해줬다.

결과는...성공 !

원인은 바로 인코딩이었다.  나는 URL주소창에 키워드가 한글로 들어가니까 인코딩을 해줘야하는 줄 알았는데 이게 문제였다. 

 

 

아래는 최종적으로 고친 코드이다.

@GetMapping에 produces를 추가해 줬다.

@Log4j2
@RestController
@RequestMapping("/api/kakaomap")
public class KakaoMapController {
	 @Autowired
	 private KakaoMapService kakaoMapService;
	 @Autowired
    private StoreService storeService;
	 
	 @GetMapping(value = "/search", produces = "application/json;charset=UTF-8")
	 public ResponseEntity<JsonNode> searchAddress(@RequestParam("keyword") String keyword) {
	
	    //결과
	    JsonNode result = kakaoMapService.searchPlaceByKeyword(keyword);
	    if (result != null) {
	        return ResponseEntity.ok(result);
	    } else {
	        return ResponseEntity.status(500).body(null);
	    }
	 }
 }
@Log4j2
@Service
public class KakaoMapService {
	
	 	private final String KAKAO_API_KEY = "발급받은 REST API 키"; 
	    private final String KAKAO_API_URL = "https://dapi.kakao.com/v2/local/search/keyword.json";
	    
	 	public JsonNode searchPlaceByKeyword(String keyword) {
	    	 try {
	    		 	
	    	        RestTemplate restTemplate = new RestTemplate();//Rest Template 객체 생성
	    	        
                    //헤더 설정을 위해 HttpHeaders클래스 생성한 후 HttpEntity 객체에 넣어줌
	    	        HttpHeaders headers = new HttpHeaders();
	    	        headers.set("Authorization", "KakaoAK " + KAKAO_API_KEY); 

	    	        HttpEntity<String> entity = new HttpEntity<>(headers);

	    	        String url = "https://dapi.kakao.com/v2/local/search/keyword.json?query=" + keyword;

	    	        // exchange()로 API 호출
	    	        ResponseEntity<JsonNode> response = restTemplate.exchange(url, HttpMethod.GET, entity, JsonNode.class);

	    	        // 결과 반환
	    	        if (response.getStatusCode().is2xxSuccessful()) {
	    	        	
	    	        	//응답 값
	    	        	JsonNode result = response.getBody();
	                   
	    	        	return result; 
	    	        } else {
	    	            System.out.println("Error: " + response.getStatusCode());
	    	            return null;
	    	        }
	    	    } catch (Exception e) {
	    	        e.printStackTrace();
	    	        return null;
	    	    }
	    	
	    }

 

=> 인코딩 부분만 삭제하고 keyword를 바로 붙여준다.

 

 

 

 

참고 : https://velog.io/@2jjong/Spring-Boot-cfxyuoze
https://velog.io/@ghwns9991/%EC%8A%A4%ED%94%84%EB%A7%81-%EB%B6%80%ED%8A%B8-3.2-%EB%A7%A4%EA%B0%9C%EB%B3%80%EC%88%98-%EC%9D%B4%EB%A6%84-%EC%9D%B8%EC%8B%9D-%EB%AC%B8%EC%A0%9C
https://velog.io/@be_have98/Spring-Boot-There-was-an-unexpected-error-typeNot-Found-status404
땡스투 swimming

 

'Spring Boot' 카테고리의 다른 글

JPA(Java Persistence API)  (0) 2024.08.21
[Spring Boot]JPA 연관관계  (0) 2024.08.20
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/09   »
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
글 보관함