微信小程序--獲取城市信息

由於微信小程序沒有方法可以獲得當前用戶所在城市的信息,所以需要調用方法來獲取城市信息,用了兩個方法去發送請求並返回城市信息
1.

@Controller
public class WechatLocationManager {

    private Logger logger = LoggerFactory.getLogger(WechatLocationManager.class);

    @RequestMapping(value = "/wechat/getcity", method = RequestMethod.POST)
    @ResponseBody
    public String getCity( @RequestBody Map<String, String> location) {
        String local = location.get("location");
        System.out.println(local);
        String latitude = local.substring(0, local.indexOf(','));
        String longitude = local.substring(local.indexOf(',') + 1);
        logger.debug("緯度:{}", latitude);
        logger.debug("經度:{}", longitude);
        String url = "http://api.map.baidu.com/geocoder/v2/?ak=2IBKO6GVxbYZvaR2mf0GWgZE&output=json&pois=0" +
            "&location=" + latitude + "," + longitude;
        HttpURLConnection connection = null;
        BufferedReader reader = null;
        try {
            URL getUrl = new URL(url);
            connection = (HttpURLConnection) getUrl.openConnection();
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            connection.connect();
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
            StringBuilder builder = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            if (logger.isDebugEnabled())
                logger.debug(builder.toString());
            return JSONObject.fromObject(builder.toString());
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                connection.disconnect();
            }
        }
        return obj;
    }
}

2.第二個方法是根據項目中提供的發送請求的方法去發送並接受返回的信息

private static final String LOCATION_URL = "http://api.map.baidu.com/geocoder/v2/";
    private static final Map<String, String> LOCATION_INPUT = new ConcurrentHashMap<String,String>(){
        {
            put("ak", "2IBKO6GVxbYZvaR2mf0GWgZE");
            put("output", "json");
            put("pois","0");
        }
    };

    @RequestMapping(value = "/wechat/city", method = RequestMethod.POST)
    @ResponseBody
    public String getCity(@RequestBody Map<String, String> location) {
        String local = location.get("location");
        System.out.println(local);
        String latitude = local.substring(0, local.indexOf(','));
        String longitude = local.substring(local.indexOf(',') + 1);
        logger.debug("緯度:{}", latitude);
        logger.debug("經度:{}", longitude);
        LOCATION_INPUT.put("location", local);
        String obj = HttpClientUtils.doGetWithHeader(null, LOCATION_URL, LOCATION_INPUT, null, "utf-8", null);
        return obj;
    }

這裏記錄一下doGet方法去處理請求的

public static String doGet(CloseableHttpClient client, String url, Map<String, String> params, String charset, String userAgent, Map<String, String> heads) {
        if (StringUtils.isBlank(url)) {
            return null;
        }
        CloseableHttpResponse response = null;
        try {
            if (params != null && !params.isEmpty()) {
                List<NameValuePair> pairs = new ArrayList<>(params.size());
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    String value = entry.getValue();
                    if (value != null) {
                        pairs.add(new BasicNameValuePair(entry.getKey(), value));
                    }
                }
                url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset));
            }
            HttpGet httpGet = new HttpGet(url);
            if (StringUtils.isNotBlank(userAgent)) {
                httpGet.addHeader(HTTP.USER_AGENT, userAgent);
            }
            if (heads != null && !heads.isEmpty()) {
                for (Map.Entry<String, String> entry : heads.entrySet()) {
                    String value = entry.getValue();
                    if (value != null) {
                        httpGet.addHeader(entry.getKey(),value);
                    }
                }
            }
            response = client.execute(httpGet);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                httpGet.abort();
                throw new RuntimeException("HttpClient,error status code :" + statusCode);
            }
            HttpEntity entity = response.getEntity();
            String result = null;
            if (entity != null) {
                result = EntityUtils.toString(entity, charset);
            }
            EntityUtils.consume(entity);
            response.close();
            return result;
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (null != response) {
                try {
                    response.close();
                } catch (Exception ex) {
                    logger.error("close response has error.");
                }
            }
        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章