package com.jyz.newapi.v1; import java.security.MessageDigest; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import org.apache.commons.codec.binary.Hex; import com.alibaba.fastjson.JSONObject; import com.gjjyz.tools.HttpUtils; public class GjjyzAPITest { static String usercode = "油客网分配的用户名"; static String key = "油客网分配的密码"; //static String baseurl = "http://www.ok619.com:8083"; static String baseurl = "http://127.0.0.1:8080/jyz2"; static public boolean sign(JSONObject params) throws Exception{ String[] kyesObjects = params.keySet().toArray(new String[] {}); Arrays.sort(kyesObjects); String stringA = ""; for(String key:kyesObjects) { String valObject = params.getString(key); if(valObject!=null && !valObject.equals("")) { if(!stringA.equals("")) stringA += "&"; stringA += key + "=" + valObject; } } stringA += "&key=" + key; String signString = getMD5(stringA).toUpperCase(); params.put("sign", signString); return true; } public static String getMD5(String info) throws Exception{ if(info==null) return ""; return Hex.encodeHexString( MessageDigest.getInstance("MD5").digest(info.getBytes("UTF-8"))); } static public String getRemote(String token, String url, JSONObject params) { Maphearder = new HashMap<>(); if(token!=null) { hearder.put("access_token", token); } if(url.startsWith("https")) { return HttpUtils.doPostSSLWithJson(url, params.toJSONString(), hearder); }else { return HttpUtils.doPostWithJson(url, params.toJSONString(), hearder); } } static public String getTimestamp() throws Exception{ //方法1,如果和中国大陆北京时间同步,那么可直接获取本地毫秒数 /** * String timestamp = String.valueOf(System.currentTimeMillis()); * return timestamp; */ //方法1:获取服务器时间戳 String url = baseurl + "/newapi/v1/auth/timestamp"; String bodyString = null; if(url.startsWith("https")) { bodyString = HttpUtils.doGetSSL(url, null, null); }else { bodyString = HttpUtils.doGet(url, null, null); } JSONObject reJsonObject = JSONObject.parseObject(bodyString); if(!reJsonObject.getString("code").equals("00")) throw new RuntimeException(reJsonObject.getString("msg")); return reJsonObject.getString("data"); } static public String getToken() throws Exception{ String timestamp = getTimestamp(); JSONObject params = new JSONObject(); params.put("usercode", usercode); params.put("timestamp", timestamp);//时间戳 sign(params); String url = baseurl + "/newapi/v1/auth/token"; String reBodyString = getRemote(null, url, params); JSONObject reJsonObject = JSONObject.parseObject(reBodyString); if(!reJsonObject.getString("code").equals("00")) throw new RuntimeException(reJsonObject.getString("msg")); String access_token = reJsonObject.getJSONObject("data").getString("access_token"); return access_token; } static public JSONObject runMethod(String method, JSONObject params) throws Exception{ String url = baseurl + "/newapi/v1/gjjyz/services/" + method; String tokenString = getToken(); if(params==null) params = new JSONObject(); params.put("usercode", usercode); params.put("timestamp", String.valueOf(System.currentTimeMillis()/1000)); if(params!=null) params.putAll(params); sign(params); String remsgString = getRemote(tokenString, url, params); JSONObject re = JSONObject.parseObject(remsgString); if("00".equals(re.getString("code"))) { return re; }else { throw new Exception("执行失败:" + remsgString); } } /** * 测试获取指定加油站明细 * @throws Exception */ public static void test_station_detail() throws Exception{ JSONObject rebody = runMethod("station/detail/1411437360", null); System.out.println(rebody.toJSONString()); } /** * 测试获取周边加油站 * @throws Exception */ public static void test_station_around() throws Exception{ JSONObject rebody = runMethod("station/around/100.2726332/16.821262", null); System.out.println(rebody.toJSONString()); } /** * 测试获取国家列表 * @throws Exception */ public static void test_country_list() throws Exception{ JSONObject rebody = runMethod("country/list", null); System.out.println(rebody.toJSONString()); } /** * 测试获取指定字典 * @throws Exception */ public static void test_dict_list() throws Exception{ JSONObject rebody = runMethod("dict/list/156/YZPP", null); System.out.println(rebody.toJSONString()); } public static void main(String[] args) throws Exception{ //测试获取国家 test_country_list(); //测试获取指定字典 test_dict_list(); //测试获取周边加油站 test_station_around(); //测试获取指定加油站 test_station_detail(); } } HttpUtils.java部分代码 -------------------------------------------------------------------------------------------------------------------------------- import javax.net.ssl.SSLContext; import org.apache.http.NameValuePair; import org.apache.http.client.ResponseHandler; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URIBuilder; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.SSLContextBuilder; import org.apache.http.conn.ssl.TrustStrategy; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; public class HttpUtils { public static CloseableHttpClient createClientDefault(boolean is_ssl) { if(is_ssl) { try { SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { // 信任所有 public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }).build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); return HttpClients.custom().setSSLSocketFactory(sslsf).build(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("创建HTTPS客户端失败!", e); } } try { return HttpClients.custom().build(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("创建HTTP客户端失败!", e); } } public static String doPostSSLPayload(String url, String jsonString, Map header) { return HttpUtils.doPostPrivate(true, createClientDefault(true), url, jsonString, header); } public static String doPostPayload(String url, String jsonString, Map header) { return HttpUtils.doPostPrivate(true, createClientDefault(false), url, jsonString, header); } private static String doPostPrivate(boolean isclose, CloseableHttpClient httpclient, String url, String jsonString, Map header) { CloseableHttpResponse response = null; try { HttpPost httpPost = new HttpPost(url); RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(15000).setConnectionRequestTimeout(30000) .setSocketTimeout(30000).build(); httpPost.setConfig(requestConfig); // 设置请求头 if (header != null) { for (String key : header.keySet()) { httpPost.addHeader(key, header.get(key)); } } StringEntity stringEntity = new StringEntity(jsonString, ContentType.APPLICATION_JSON); httpPost.setEntity(stringEntity); response = httpclient.execute(httpPost); int statusCode = response.getStatusLine().getStatusCode(); if (200 == statusCode) { /** * 通过EntityUitls获取返回内容 */ String result = EntityUtils.toString(response.getEntity(),"UTF-8"); return result; }else { throw new RuntimeException("请求返回错误:statusCode=" + statusCode); } } catch (Exception e) { e.printStackTrace(); try { if (response != null) response.close(); } catch (Exception e1) { } try { if(isclose && httpclient != null) httpclient.close(); } catch (Exception e1) { } throw new RuntimeException("请求返回错误!", e); } } ... }