HD

[NAVER] 네아로 API 연동 (2) 본문

API/NAVER

[NAVER] 네아로 API 연동 (2)

hunecenter 2019. 10. 25. 10:50
반응형

1.AccessToken 처리

	/**
	 * NAVER AccessToken 처리
	 * @param authorize_code
	 * @return
	 */
	@Override
	public String getNaverAccessToken (String authorize_code) {
			String access_Token = "";
			String reqURL = "https://nid.naver.com/oauth2.0/token";
			
	        try {
	            URL url = new URL(reqURL);
	            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
	            
	            //POST 요청을 위해 기본값이 false인 setDoOutput을 true로
	            conn.setRequestMethod("POST");
	            conn.setDoOutput(true);
	            //POST 요청에 필요로 요구하는 파라미터 스트림을 통해 전송
	            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
	            StringBuilder sb = new StringBuilder();
	            sb.append("grant_type=authorization_code");
	            sb.append("&client_id=client_id");
	            sb.append("&client_secret=client_secret");
	            sb.append("&redirect_uri=redirect_uri");
	            sb.append("&code="+authorize_code);
	            sb.append("&state=url_parameter");
	            bw.write(sb.toString());
	            bw.flush();
	            
	            //결과 코드가 200이라면 성공
	            int responseCode = conn.getResponseCode();
	            if(responseCode==200){
		            //요청을 통해 얻은 JSON타입의 Response 메세지 읽어오기
		            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		            String line = "";
		            String result = "";
		            
		            while ((line = br.readLine()) != null) {
		                result += line;
		            }
		            
		            //Gson 라이브러리에 포함된 클래스로 JSON파싱 객체 생성
		            JsonParser parser = new JsonParser();
		            JsonElement element = parser.parse(result);
		            
		            access_Token = element.getAsJsonObject().get("access_token").getAsString();
		          //refresh_Token = element.getAsJsonObject().get("refresh_token").getAsString();
		            br.close();
		            bw.close();
	            }
	        } catch (IOException e) {
	            e.printStackTrace();
	        } 
	        
	        return access_Token;
	    }

2.네이버 유저정보

	/**
	 * NAVER USER INFO
	 * @param access_Token
	 */
	@Override
	public void getNaverUserInfo (String access_Toke) {
	    //요청하는 클라이언트마다 가진 정보가 다를 수 있기에 HashMap타입으로 선언
	    HashMap<String, Object> naverUserInfo = new HashMap<>();
	    String reqURL = "https://openapi.naver.com/v1/nid/me";
	    try {
	        URL url = new URL(reqURL);
	        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
	        conn.setRequestMethod("POST");
	        
	        //요청에 필요한 Header에 포함될 내용
	        conn.setRequestProperty("Authorization", "Bearer " + access_Token);
	        
	        int responseCode = conn.getResponseCode();
	        if(responseCode == 200){
		        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		        
		        String line = "";
		        String result = "";
		        
		        while ((line = br.readLine()) != null) {
		            result += line;
		        }
		        JsonParser parser = new JsonParser();
		        JsonElement element = parser.parse(result);
		        
		        JsonObject response = element.getAsJsonObject().get("response").getAsJsonObject();
		        
		        String name = response.getAsJsonObject().get("name").getAsString();
		        String email = response.getAsJsonObject().get("email").getAsString();
		        String id = "NAVER_"+response.getAsJsonObject().get("id").getAsString();
		        
		        naverUserInfo.put("name", name);
		        naverUserInfo.put("email", email);
		        naverUserInfo.put("id", id);
		        
	        }
	    } catch (IOException e) {
	        e.printStackTrace();
	    }
	}

3.Controller

	/** 
    * sns Login 
    */ 
    @RequestMapping( "/index" ) 
    public String view(
    	ModelMap model ) { 
        String naverUrl = "https://nid.naver.com/oauth2.0/authorize?response_type=code&client_id=client_id&redirect_uri=redirect_uri&state=url_parameter";
        model.addAttribute( "naverUrl", naverUrl ); 
        return "/index"; 
     }
     
    /**
	 * NAVER Login 
	 * @param code
	 * @throws IOException 
	 */
	@RequestMapping( "/naverLogin" )
	public void  naverLogin(
			@RequestParam("code") String code,
			HttpServletResponse response) throws IOException {
		String access_Token = snsLoginService.getAccessToken(code);
	
		String referer = (String)request.getHeader("REFERER")!=null? (String)request.getHeader("REFERER") : "http://localhost:8080";
		
		snsLoginService.getUserInfo(access_Token);
		
		response.setContentType("text/html; charset=UTF-8");
        PrintWriter out = response.getWriter();
        //Login Popup창 닫고 page referer url로 새로고침
        out.println("<script>window.close(); opener.parent.location="+"'"+referer+"'"+";</script>");
        out.flush();
	}

4.index.jsp

<a id="custom-login-btn" href="javascript:void(0);" onclick="window.open('${naverUrl}','naverLogin','width=430,height=500,location=no,status=no,scrollbars=yes');"">
	<img src="http://static.nid.naver.com/oauth/small_w_in.PNG" width="100"/>
</a>

 

반응형

'API > NAVER' 카테고리의 다른 글

[NAVER] 네아로 API 연동 (1)  (0) 2019.10.24
Comments