通过API获取定位、手机等

一、获取ip

	public String findIp(HttpServletRequest request){
		String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_CLIENT_IP"); }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_X_FORWARDED_FOR"); }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); }
        return ip;
        }

二、使用百度接口根据ip获取定位

只能获取省

String url="http://api.map.baidu.com/location/ip?ak=百度控制台创建&ip=获取ip地址";
JSONObject jsonObject = readJsonFromUrl(url);

public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
        InputStream is = new URL(url).openStream();
        try {
            BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
            String line = null;
            String message = new String();
            while ((line = rd.readLine()) != null) {
                message += line;
            }
            JSONObject json = new JSONObject(message);
            return json;
        } finally {
            is.close();
        }
    }

三、阿里云手机号码归属地查询接口

只能获取省+市
阿里云手机号码归属地查询

String host = "https://jshmgsdmfb.market.alicloudapi.com";
	    String path = "/shouji/query";
	    String method = "GET";
	    String appcode = "你自己的AppCode";
	    Map<String, String> headers = new HashMap<String, String>();
	    //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
	    headers.put("Authorization", "APPCODE " + appcode);
	    Map<String, String> querys = new HashMap<String, String>();
	    querys.put("shouji", "13456755448");


	    try {
	    	/**
	    	* 重要提示如下:
	    	* HttpUtils请从
	    	* https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
	    	* 下载
	    	*
	    	* 相应的依赖请参照
	    	* https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
	    	*/
	    	//HttpUtils百度搜一下就有的工具类包
	    	HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
	    	System.out.println(response.toString());
	    	//获取response的body
	    	System.out.println(EntityUtils.toString(response.getEntity(),"utf-8"));
	    } catch (Exception e) {
	    	e.printStackTrace();
	    }
<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpcore</artifactId>
	<version>4.2.1</version>
</dependency>

四、vx小程序登录java服务器获取用户手机

重点:小程序在本地环境下微信开发者工具里测试,拿到的encryptedData、iv只能在本地开发环境下的java服务器才能解密成功
以上这句话整的我两天时间调错,后续才发现小丑是我

①、encryptedData解码时,报Illegal base64 character 3f错误
或者解码完byte[]为空或者key is empty
在这里插入图片描述在这里插入图片描述

②、byte[] doFinal = cipher.doFinal(encrypData)
报Input length must be multiple of 16 when decrypting with padded cipher错误

import java.util.Base64;
换成
import org.apache.commons.codec.binary.Base64;
解码没问题
在这里插入图片描述
在这里插入图片描述
附上成功的代码

//appId和appSecret在小程序开发者里查询
String appId="xxxxxxx";
String appSecret="xxxxxxx";
String requestUrl = "https://api.weixin.qq.com/sns/jscode2session";
Map<String,String> requestUrlParam = new HashMap<String,String>();
requestUrlParam.put("appid", appId); //开发者设置中的appId
requestUrlParam.put("secret", appSecret); //开发者设置中的appSecret
requestUrlParam.put("js_code", code); //小程序调用wx.login返回的code
requestUrlParam.put("grant_type", "authorization_code");  //默认参数
//发送post请求读取调用微信 https://api.weixin.qq.com/sns/jscode2session 接口获取openid用户唯一标识
JSONObject jsonObject = JSONUtil.parseObj(UrlUtil.sendPost(requestUrl, requestUrlParam));

String openId = (String)jsonObject.get("openid");
if(openId==null || jsonObject.toString().length()==0){ return new Result<String>(false, StatusCode.ERROR, "code无效",jsonObject); }

String sessionKey = (String)jsonObject.get("session_key");
Map data = UrlUtil.decodePhoneNum(encryptedData, sessionKey, iv);

UrlUtil工具包,我将解密方法也放里面了

public class UrlUtil {

        /**
         * 向指定URL发送GET方法的请求
         *
         * @param url
         *            发送请求的URL
         * @param param
         *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
         * @return URL 所代表远程资源的响应结果
         */
        public static String sendGet(String url, String param) {
            String result = "";
            BufferedReader in = null;
            try {
                String urlNameString = url + "?" + param;
                URL realUrl = new URL(urlNameString);
                // 打开和URL之间的连接
                URLConnection connection = realUrl.openConnection();
                // 设置通用的请求属性
                connection.setRequestProperty("accept", "*/*");
                connection.setRequestProperty("connection", "Keep-Alive");
                connection.setRequestProperty("user-agent",
                        "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
                // 建立实际的连接
                connection.connect();
                // 获取所有响应头字段
                Map<String, List<String>> map = connection.getHeaderFields();
                // 遍历所有的响应头字段
                for (String key : map.keySet()) {
                    System.out.println(key + "--->" + map.get(key));
                }
                // 定义 BufferedReader输入流来读取URL的响应
                in = new BufferedReader(new InputStreamReader(
                        connection.getInputStream()));
                String line;
                while ((line = in.readLine()) != null) {
                    result += line;
                }
            } catch (Exception e) {
                System.out.println("发送GET请求出现异常!" + e);
                e.printStackTrace();
            }
            // 使用finally块来关闭输入流
            finally {
                try {
                    if (in != null) {
                        in.close();
                    }
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
            }
            return result;
        }

        /**
         * 向指定 URL 发送POST方法的请求
         *
         * @param url
         *            发送请求的 URL
         * @param paramMap
         *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
         * @return 所代表远程资源的响应结果
         */
        public static String sendPost(String url, Map<String, ?> paramMap) {
            PrintWriter out = null;
            BufferedReader in = null;
            String result = "";

            String param = "";
            Iterator<String> it = paramMap.keySet().iterator();

            while(it.hasNext()) {
                String key = it.next();
                param += key + "=" + paramMap.get(key) + "&";
            }

            try {
                URL realUrl = new URL(url);
                // 打开和URL之间的连接
                URLConnection conn = realUrl.openConnection();
                // 设置通用的请求属性
                conn.setRequestProperty("accept", "*/*");
                conn.setRequestProperty("connection", "Keep-Alive");
                conn.setRequestProperty("Accept-Charset", "utf-8");
                conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
                // 发送POST请求必须设置如下两行
                conn.setDoOutput(true);
                conn.setDoInput(true);
                // 获取URLConnection对象对应的输出流
                out = new PrintWriter(conn.getOutputStream());
                // 发送请求参数
                out.print(param);
                // flush输出流的缓冲
                out.flush();
                // 定义BufferedReader输入流来读取URL的响应
                in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
                String line;
                while ((line = in.readLine()) != null) {
                    result += line;
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
            //使用finally块来关闭输出流、输入流
            finally{
                try{
                    if(out!=null){
                        out.close();
                    }
                    if(in!=null){
                        in.close();
                    }
                }
                catch(IOException ex){
                    ex.printStackTrace();
                }
            }
            return result;
        }

        //获取小程序用户信息
    public  static Map decodePhoneNum(String encryptedData, String sessionKey, String iv) {
        try {

            Base64.Decoder decoder = Base64.getDecoder();
            byte[] sessionKeyBytes = decoder.decode(sessionKey);
           // System.out.println(sessionKeyBytes);
            byte[] ivBytes = decoder.decode(iv);
           // System.out.println(ivBytes);
            byte[] encryptedBytes = decoder.decode(encryptedData);

            //System.out.println(encryptedBytes);

            // JDK does not support PKCS7Padding, use PKCS5Padding instead
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec skeySpec = new SecretKeySpec(sessionKeyBytes, "AES");
            IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivSpec);
            byte[] ret = cipher.doFinal(encryptedBytes);
            return (Map) JSONUtils.parse(new String(ret));
        } catch (Exception e) {
            e.printStackTrace();

        }
        return null;
    }
}
<!--   vx小程序登录验证     -->
<dependency>
    <groupId>org.codehaus.xfire</groupId>
    <artifactId>xfire-core</artifactId>
    <version>1.2.6</version>
</dependency>
<dependency>
    <groupId>org.bouncycastle</groupId>
    <artifactId>bcprov-jdk16</artifactId>
    <version>1.46</version>
</dependency>
  • 6
    点赞
  • 73
    收藏
    觉得还不错? 一键收藏
  • 12
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值