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<String,String> tokenHeadMap = new HashMap<String,String>();
		tokenHeadMap.put("Content-Type", "application/x-www-form-urlencoded");
		MultiValueMap<String,String> bodyMap = new LinkedMultiValueMap<String,String>();
		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<String, String> header = new LinkedMultiValueMap<>();
		header.add("Content-Type", "application/x-www-form-urlencoded");
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(bodyMap, header);
        RestTemplate restTemplate = new RestTemplate();
        Map<String,String> params = new HashMap<>();
        ResponseEntity<Map> forEntity = restTemplate.postForEntity(TOKEN_URL, request, Map.class, params);
        if(forEntity != null)
        {
        	String token = forEntity.getBody().get("access_token").toString();
    		Map<String,String> headerMap = new HashMap<String,String>();
    		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<String,Object> dataMap = (Map<String,Object>)responesEntity.getBody();
    			id = dataMap.get("id").toString();
    			displayName = dataMap.get("displayName").toString();
    			language = dataMap.get("language").toString();
    			List<Map<String,String>> emails = (List<Map<String,String>>)dataMap.get("emails");
    			if(emails != null && emails.size() != 0)
    			{
    				Map<String,String> emailObj = (Map<String,String>)emails.get(0);
    				email = emailObj.get("value");
    				email = email.replace("\\u0040", "@");
    			}
    			
    			Map<String,String> imageMap = (Map<String,String>)dataMap.get("image");
    			if(imageMap != null)
    			{
    				icon = imageMap.get("url");
    				icon = icon.replace("?sz=50", "?sz=500");
    			}
    			
    			Map<String,Object> coverObj = (Map<String,Object>)dataMap.get("cover");
    			if(coverObj != null)
    			{
    				Map<String,String> coverPhotoObj = (Map<String,String>)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<String,String> headerMap){
	    	logger.info("sendHttp URL  "+ url);
	        if(entity == null){
	            entity = new Object();
	        }
	        Map<String,String> params = new HashMap<>();
	        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
	        HttpHeaders headers = new HttpHeaders();
	        headers.setContentType(type);
	        for(Map.Entry<String , String> entry : headerMap.entrySet()){
	            headers.set(entry.getKey() ,entry.getValue() );
	        }
	        HttpEntity<String> 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);
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值