google登录 java获取用户信息

google api




/**
 * 
 */
package com.xx.sns.business.impl.login;

import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.Proxy.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSONObject;




public class GoogleLoginBiz 
{
	private static final Logger logger = LoggerFactory.getLogger(GoogleLoginBiz.class);
	
	
	//浏览器请求获取code   https://accounts.google.com/o/oauth2/v2/auth?response_type=code&client_id={CLIENT_ID}&redirect_uri={BACK_URL}&scope=profile&state=1&access_type=offline
	private static final String USERINFO_URL =  "https://www.googleapis.com/plus/v1/people/me";
	
	private static final String TOKEN_URL = "https://www.googleapis.com/oauth2/v4/token";
	
	private static final String BACK_URL = "http://xxxxxxx.xxx.com/oauth2callback";
	
	
	
	private static final String CLIENT_ID="xxxxxxxx.apps.googleusercontent.com";
	private static final String CLIENT_SECRET="xxxxxxxxxx";
	
	
	public UserInfoPo login(String code)  {
		
		//获取token
		Map tokenHeadMap = new HashMap();
		tokenHeadMap.put("Content-Type", "application/x-www-form-urlencoded");
		MultiValueMap bodyMap = new LinkedMultiValueMap();
		bodyMap.add("code", code);
		bodyMap.add("client_id", CLIENT_ID);
		bodyMap.add("client_secret", CLIENT_SECRET);
		bodyMap.add("redirect_uri", BACK_URL);
		bodyMap.add("grant_type", "authorization_code");
		
		MultiValueMap header = new LinkedMultiValueMap<>();
		header.add("Content-Type", "application/x-www-form-urlencoded");
        HttpEntity> request = new HttpEntity<>(bodyMap, header);
        RestTemplate restTemplate = new RestTemplate();
        Map params = new HashMap<>();
        ResponseEntity forEntity = restTemplate.postForEntity(TOKEN_URL, request, Map.class, params);
        if(forEntity != null)
        {
        	String token = forEntity.getBody().get("access_token").toString();
    		Map headerMap = new HashMap();
    		headerMap.put("Authorization", "Bearer "+token);
    		headerMap.put("Content-Type", "application/x-www-form-urlencoded");
    		ResponseEntity  responesEntity =  sendHttp(USERINFO_URL, null, HttpMethod.GET, Map.class, headerMap);
    		if(responesEntity != null)
    		{
    			logger.info(ReflectionToStringBuilder.toString(responesEntity));
    			String email = "";
    			String id = "";
    			String displayName = "";
    			String icon = "";
    			String bgImage = "";
    			String language = "";
    			Map dataMap = (Map)responesEntity.getBody();
    			id = dataMap.get("id").toString();
    			displayName = dataMap.get("displayName").toString();
    			language = dataMap.get("language").toString();
    			List> emails = (List>)dataMap.get("emails");
    			if(emails != null && emails.size() != 0)
    			{
    				Map emailObj = (Map)emails.get(0);
    				email = emailObj.get("value");
    				email = email.replace("\\u0040", "@");
    			}
    			
    			Map imageMap = (Map)dataMap.get("image");
    			if(imageMap != null)
    			{
    				icon = imageMap.get("url");
    				icon = icon.replace("?sz=50", "?sz=500");
    			}
    			
    			Map coverObj = (Map)dataMap.get("cover");
    			if(coverObj != null)
    			{
    				Map coverPhotoObj = (Map)coverObj.get("coverPhoto");
    				bgImage =  coverPhotoObj.get("url");
    			}
    			UserInfoPo userPo = new UserInfoPo();
    			userPo.setLoginId(id);
    			userPo.setEmail(email);
    			userPo.setIcon(icon);
    			userPo.setBgIcon(bgImage);
    			userPo.setType(UserType.GOOGLE);
    			userPo.setLanguage(language);
    			userPo.setName(displayName);
    			userPo.setGender(CommConstants.GenderType.Secret);
    			return userPo;
    		}
        }
        return null;
	}
	
	
	 public  ResponseEntity sendHttp(String url,Object entity, HttpMethod method, Class clazz , Map headerMap){
	    	logger.info("sendHttp URL  "+ url);
	        if(entity == null){
	            entity = new Object();
	        }
	        Map params = new HashMap<>();
	        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
	        HttpHeaders headers = new HttpHeaders();
	        headers.setContentType(type);
	        for(Map.Entry entry : headerMap.entrySet()){
	            headers.set(entry.getKey() ,entry.getValue() );
	        }
	        HttpEntity formEntity = new HttpEntity<>(JSONObject.toJSONString(entity), headers);
	        try {
	        	SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
	    	    Proxy proxy= new Proxy(Type.HTTP, new InetSocketAddress("192.168.8.223", 7777));
	    	    requestFactory.setProxy(proxy);
	            RestTemplate restTemplate = new RestTemplate();
	            ResponseEntity response = restTemplate.exchange(url, method, formEntity, clazz, params);
	            logger.info("response body: {}" , response.getBody());
	            return response;
	        } catch (Exception e){
	            logger.error(e.getMessage());
	        }
	        return null;
	    }
	
	public static void main(String[] args) {
		//获取像素高点的头像
		String icon = "https://lh5.googleusercontent.com/-HXYa7raiCNY/AAAAAAAAAAI/AAAAAAAAABU/BYkIyqdmTWc/photo.jpg?sz=50";
		icon = icon.replace("?sz=50", "?sz=500");
		System.out.println(icon);
	}
}



你可能感兴趣的:(google登录 java获取用户信息)