主题
Java
java
package demo;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import okhttp3.*;
import com.qiniu.util.Json;
import com.qiniu.util.StringUtils;
import com.qiniu.util.Auth;
/**
* 域名: api.niulinkcloud.com
*
* maven坐标
* <dependency>
* <groupId>com.qiniu</groupId>
* <artifactId>qiniu-java-sdk</artifactId>
* <version>7.15.0</version>
* </dependency>
*
* <dependency>
* <groupId>com.squareup.okhttp3</groupId>
* <artifactId>okhttp</artifactId>
* <version>5.0.0-alpha.11</version>
* </dependency>
*/
public class JavaDemo {
public static String ak = "你的ak";
public static String sk = "你的sk";
public static final String QINIU_AUTHORIZATION_PREFIX = "Qiniu ";
public static void main(String[] args) throws Exception {
get();
post();
}
public static void get() throws Exception {
Map<String, String> reqMap = new HashMap<>();
reqMap.put("province", "江苏");
reqMap.put("isp", "移动");
reqMap.put("usbw", "1000");
reqMap.put("bwNum", "5");
reqMap.put("natType", "public");
reqMap.put("dialType", "staticNetSingle");
String url = "https://api.niulinkcloud.com/v1/vendorclaimablebw?" + buildQueryParam(reqMap);
Auth auth = Auth.create(ak, sk);
String authorization = QINIU_AUTHORIZATION_PREFIX + auth.signQiniuAuthorization(url, "GET", (byte[])null, (String)null);
OkHttpClient client = new OkHttpClient.Builder().build();
Request request = new Request.Builder()
.header("Authorization", authorization)
.url(url)
.get()
.build();
Call call = client.newCall(request);
String resp = call.execute().body().string();
System.out.println(resp);
}
public static void post() throws Exception {
// 接口的完整请求url : 域名+path
String url = "https://api.niulinkcloud.com/v1/nodes/stats";
// 组装接口逻辑处理的请求参数
Map<String, Object> bodyMap = new HashMap<>();
bodyMap.put("nodeIDs", new String[]{"你的节点ID"});
bodyMap.put("start", "2024-03-26");
bodyMap.put("end", "2024-03-27");
String reqJsonData = Json.encode(bodyMap);
// 具体签名
Auth auth = Auth.create(ak, sk);
String authorization = QINIU_AUTHORIZATION_PREFIX + auth.signQiniuAuthorization(url, "POST", StringUtils.utf8Bytes(reqJsonData), "application/json");
RequestBody reqBody = RequestBody.create(StringUtils.utf8Bytes(reqJsonData));
Request request = new Request.Builder()
.header("Authorization", authorization)
.header("Content-Type", "application/json")
.url(url)
.post(reqBody)
.build();
OkHttpClient client = new OkHttpClient.Builder().build();
Call call = client.newCall(request);
String resp = call.execute().body().string();
System.out.println(resp);
}
public static String buildQueryParam(Map<String, String> map) throws Exception {
String result = "";
Set<String> set = map.keySet();
for (String key : set) {
result += key + "=" + URLEncoder.encode(map.get(key), "UTF-8") + "&";
}
return result.substring(0, result.length() - 1);
}
}