Java - okhttp3 call API interface Official Website
This article uses java to call a class API interface as an example, and the signature needs to be obtained by performing sha1 encryption algorithm after dictionary sorting by map key. The address of the API document with classes: https://postman.mudu.tv/?version=latest
Dictionary sorting
The following two methods can be used to sort the dictionary:
Method 1:
// 对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;
}
Method 2:
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 algorithm to calculate the signature
/**
* 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("签名错误!");
}
}
Generate ten-digit timestamp
public static String getTimeStamp() {
return String.valueOf(System.currentTimeMillis() / 1000);
}
Examples
Call the public viewing-login interface with a synchronous post request:
/**
* 以同步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×tamp=" + 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();
}
}
Use the synchronous get request to call the public viewing-token login to jump to the viewing page:
/**
* 以同步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×tamp="
+ 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();
}
}