由于微信小程序没有方法可以获得当前用户所在城市的信息,所以需要调用方法来获取城市信息,用了两个方法去发送请求并返回城市信息
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 = "https://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 = "https://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."); } } } }