Java——okhttp3调用API接口

Java——okhttp3调用API接口 官方网站

本篇以java调用有课API接口为例,签名须要以map的key进行字典排序以后进行sha1加密算法后得出。有课API文档地址:https://postman.mudu.tv/?version=latestphp

字典排序

   如下提供的两种方式均可以进行字典排序:
   方式一:java

// 对map中的数据以key进行字典排序
 public static String sortMapKey(Map<String, String> map) {
     // 将map放入到List中
     List<Map.Entry<String, String>> keys = new ArrayList<>(map.entrySet());
     // 排序
     keys.sort(Comparator.comparing(o -> (o.getKey())));
     StringBuffer buf = new StringBuffer("{"); // 循环构建键值对字符串
     for (Map.Entry<String, String> item : keys) {
         if (StringUtils.isNotBlank(item.getKey())) {
             String key = item.getKey();
             String val = item.getValue();
             buf.append("\"").append(key).append("\"").append(":").append("\"").append(val).append("\"").append(",");
         }
     }
     String buff = buf.toString();
     if (!buff.isEmpty()) {
         buff = buff.substring(0, buff.length() - 1)+"}";
     }
     return buff;
 }

   方式二:git

public static String sortMapKey1(Map<String, String> map) {
	Collection<String> keyset = map.keySet();
	List<String> list = new ArrayList<String>(keyset);
	Collections.sort(list);
	JSONObject jsonObject = new JSONObject(true);
	for (int i = 0; i < list.size(); i++) {
		jsonObject.put(list.get(i).toString(), map.get(list.get(i)));
	}
	return jsonObject.toJSONString();
}
sha1算法算出签名
/** * SHA1安全加密算法 * * @param maps * @return * @throws DigestException */
public static String shaSign(Map<String, String> maps) throws DigestException {
	// 获取信息摘要-参数排序后字符串
	String decrypt = sortMapKey(maps);
	System.out.println(decrypt);
	try {
		// 指定sha1算法 
		MessageDigest digest = MessageDigest.getInstance("SHA-1");
		// Updates the digest using the specified array of bytes.
		digest.update(decrypt.getBytes());
		// 获取字节数组 
		byte messageDigest[] = digest.digest();
		// CreateHexString 
		StringBuffer hexString = new StringBuffer();
		// 字节数组转换为十六进制数 
		for (int i = 0; i < messageDigest.length; i++) {
			String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
			if (shaHex.length() < 2) {
				hexString.append(0);
			}
			hexString.append(shaHex);
		}
		return hexString.toString();
	} catch (NoSuchAlgorithmException e) {
		e.printStackTrace();
		throw new DigestException("签名错误!");
	}
}
生成十位时间戳
public static String getTimeStamp() {
	return String.valueOf(System.currentTimeMillis() / 1000);
}
示例

   以同步post请求调用公众观看-登陆接口:github

/** * 以同步post请求调用公众观看-登陆接口 * * @throws DigestException */
static void publicLogin() throws DigestException {
	HashMap<String, String> map = new HashMap<>();
	map.put("access_key", "填本身的access_key");
	map.put("secret_key", "填本身的secret_key");
	map.put("id", "jnwpCAqFiI8KeFCovh7U7fA2pPljmDqz");
	map.put("name", "test");
	map.put("timestamp", getTimeStamp());
	//获得签名
	String sign = shaSign(map);
	OkHttpClient okHttpClient = new OkHttpClient();
	// 参数
	RequestBody body = new FormBody.Builder().add("name", map.get("name")).add("id", map.get("id")).build();
	// post请求
	Request request = new Request.Builder()
			.url("http://youke.mudu.tv/Index.php?c=session&a=anonymousLogin&timestamp=" + map.get("timestamp")
					+ "&access_key=" + map.get("access_key") + "&sign=" + sign)
			.post(body).build();
	Response response = null;
	try {
		// execute()方法表示同步请求,如需异步请求调用enqueue()方法
		response = okHttpClient.newCall(request).execute();
		String str = response.body().string();
		JSONObject json = JSONObject.parseObject(str);
		//调用公开观看-token登陆跳转观看页
		publicLoginDetail(json.getString("data"));
	} catch (IOException e) {
		e.printStackTrace();
	}
}

   以同步get请求调用公开观看-token登陆跳转观看页:web

/** * 以同步get请求调用公开观看-token登陆跳转观看页 * * @param audience_token * @throws DigestException */
static void publicLoginDetail(String audience_token) throws DigestException {
	HashMap<String, String> map = new HashMap<>();
	map.put("access_key", "填本身的access_key");
	map.put("secret_key", "填本身的secret_key");
	map.put("id", "jnwpCAqFiI8KeFCovh7U7fA2pPljmDqz");
	map.put("audience_token", audience_token);
	map.put("timestamp", getTimeStamp());
	//获得签名
	String sign = shaSign(map);
	OkHttpClient okHttpClient = new OkHttpClient();
	// get请求
	Request request = new Request.Builder().url("http://youke.mudu.tv/Index.php?c=session&a=sessionLogin&timestamp="
			+ map.get("timestamp") + "&access_key=" + map.get("access_key") + "&sign=" + sign + "&id="
			+ map.get("id") + "&audience_token=" + map.get("audience_token")).get().build();
	System.out.println(request);
	Response response = null;
	try {
		response = okHttpClient.newCall(request).execute();
		String str = response.body().string();
		System.out.println(str);
	} catch (IOException e) {
		e.printStackTrace();
	}
}