Skip to content

Instantly share code, notes, and snippets.

@phosae
Last active February 17, 2023 03:50
Show Gist options
  • Save phosae/4ffb84ce5e5d2a6ec15b70a266dea040 to your computer and use it in GitHub Desktop.
Save phosae/4ffb84ce5e5d2a6ec15b70a266dea040 to your computer and use it in GitHub Desktop.
treenity
package dev.zeng.util;
import okhttp3.*;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;
public class OkHttpUtils {
private static volatile OkHttpClient okHttpClient = null;
public static void init() {
if (okHttpClient == null) {
synchronized (OkHttpUtils.class) {
if (okHttpClient == null) {
okHttpClient = new OkHttpClient.Builder()
.connectTimeout(15, TimeUnit.SECONDS)
.writeTimeout(20, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.retryOnConnectionFailure(true)
.build();
}
}
}
}
private static String wrapJsonBody(int code, String raw, String statusCodeMsg) {
if (code >= 200 && code < 300) {
return "{" +
"\"code\":" + code + ", " + "\"msg\": \"\", " + "\"data\": " + raw +
"}";
} else if (code >= 400 && code < 500) {
return "{" +
"\"code\":" + code + ", " + "\"msg\": \"" + raw + "\"" +
"}";
} else {
return "{" +
"\"code\":" + code + ", " + "\"msg\": \"" + statusCodeMsg + "|"+ raw + "\"" +
"}";
}
}
/**
* get 请求
*
* @param url
* @param headerMap
* @return
* @throws Exception
*/
@SuppressWarnings("ConstantConditions")
public static String get(String url, Map<String, String> headerMap) throws Exception {
Request.Builder builder = new Request.Builder().url(url);
if (headerMap != null && !headerMap.isEmpty()) {
headerMap.forEach(builder::addHeader);
}
Request request = builder.get().build();
try (Response resp = okHttpClient.newCall(request).execute()) {
return OkHttpUtils.wrapJsonBody(resp.code(), resp.body().string(), resp.message());
}
}
/**
* 初始化post方法
*
* @return
*/
@SuppressWarnings("ConstantConditions")
public static String post(String url, String json, Map<String, String> headerMap) throws IOException {
RequestBody requestBody = RequestBody.create(json, MediaType.parse("application/json; charset=utf-8"));
Request.Builder builder = new Request.Builder().url(url);
if (headerMap != null && !headerMap.isEmpty()) {
headerMap.forEach(builder::addHeader);
}
Request request = builder.post(requestBody).build();
try (Response resp = okHttpClient.newCall(request).execute()) {
return OkHttpUtils.wrapJsonBody(resp.code(), resp.body().string(), resp.message());
}
}
/**
* delete方法
*
* @return
*/
public static String delete(String url, Map<String, String> headerMap) throws IOException {
Request.Builder builder = new Request.Builder().url(url);
if (headerMap != null && !headerMap.isEmpty()) {
headerMap.forEach(builder::addHeader);
}
Request request = builder.delete().build();
try (Response resp = okHttpClient.newCall(request).execute()) {
return OkHttpUtils.wrapJsonBody(resp.code(), resp.body().string(), resp.message());
}
}
/**
* put方法
*
* @return
*/
public static String put(String url, String json, Map<String, String> headerMap) throws IOException {
RequestBody requestBody = RequestBody.create(json, MediaType.parse("application/json; charset=utf-8"));
Request.Builder builder = new Request.Builder().url(url);
if (headerMap != null && !headerMap.isEmpty()) {
headerMap.forEach(builder::addHeader);
}
Request request = builder.put(requestBody).build();
try (Response resp = okHttpClient.newCall(request).execute()) {
return OkHttpUtils.wrapJsonBody(resp.code(), resp.body().string(), resp.message());
}
}
}
package demo.zeng.dev;
import com.qiniu.util.Auth;
import okhttp3.*;
import okio.Buffer;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
public class QappIngressDemo {
private static volatile OkHttpClient okHttpClient = null;
public static void init() {
if (okHttpClient == null) {
synchronized (QappIngressDemo.class) {
if (okHttpClient == null) {
okHttpClient = new OkHttpClient.Builder()
.connectTimeout(15, TimeUnit.SECONDS)
.writeTimeout(20, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.retryOnConnectionFailure(true)
.build();
}
}
}
}
public static String get(String url, Map<String, String> headerMap) throws Exception {
Request.Builder builder = new Request.Builder().url(url);
if (headerMap != null && !headerMap.isEmpty()) {
headerMap.forEach(builder::addHeader);
}
Request request = newRequestWithQiniuAuthorization(builder.get().build());
try (Response resp = okHttpClient.newCall(request).execute()) {
return resp.body().string();
}
}
private static final String QINIU_AK = "<改成你的七牛 AccessKey>";
private static final String QINIU_SK = "<改成你的七牛 SecretKey>";
public static Request newRequestWithQiniuAuthorization(Request request) throws IOException {
final Request copy = request.newBuilder().build();
final Buffer buffer = new Buffer();
if (copy.body() != null) {
copy.body().writeTo(buffer);
}
Auth auth = Auth.create(QINIU_AK, QINIU_SK);
Map<String,String> headersMap = new HashMap<>();
copy.headers().forEach((h)->{
String hk = h.getFirst();
String hv = h.getSecond();
headersMap.put(hk,hv);
});
com.qiniu.http.Headers qHeaders = com.qiniu.http.Headers.of(headersMap);
String token = auth.signQiniuAuthorization(copy.url().toString(),copy.method().toString(), buffer.readByteArray(),qHeaders );
return request.newBuilder().addHeader("Authorization", "Qiniu " + token).build();
}
public static void main(String []args) throws Exception{
init();
System.out.println(get("https://<改成你的app名>.service-cn-east-2.qiniuapp.com/net",null));
}
}
/*
<dependencies>
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
<version>[7.12.0, 7.12.99]</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.10.0</version>
</dependency>
<dependency>
<groupId>com.squareup.okio</groupId>
<artifactId>okio</artifactId>
<version>3.0.0</version>
</dependency>
</dependencies>
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment