forked from ConvertAPI/convertapi-library-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHttp.java
More file actions
91 lines (78 loc) · 3.08 KB
/
Http.java
File metadata and controls
91 lines (78 loc) · 3.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package com.convertapi;
import com.convertapi.model.RemoteUploadResponse;
import com.google.gson.Gson;
import okhttp3.*;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
class Http {
private static final OkHttpClient client = new OkHttpClient();
static OkHttpClient getClient() {
return client;
}
static OkHttpClient getClient(Config config) {
return config.getHttpClientBuilder()
.apply(getClient().newBuilder())
.readTimeout(config.getTimeout() + 5, TimeUnit.SECONDS)
.build();
}
static HttpUrl.Builder getUrlBuilder(Config config) {
return new HttpUrl.Builder()
.scheme(config.getScheme())
.host(config.getHost())
.addQueryParameter("timeout", String.valueOf(config.getTimeout()))
.addQueryParameter("secret", config.getSecret());
}
static CompletableFuture<InputStream> requestGet(String url) {
return CompletableFuture.supplyAsync(() -> {
Request request = getRequestBuilder().url(url).build();
Response response;
try {
response = getClient().newCall(request).execute();
} catch (IOException e) {
throw new RuntimeException(e);
}
//noinspection ConstantConditions
return response.body().byteStream();
});
}
static CompletableFuture<Void> requestDelete(String url) {
return CompletableFuture.supplyAsync(() -> {
Request request = getRequestBuilder().delete().url(url).build();
try {
getClient().newCall(request).execute();
} catch (IOException e) {
throw new RuntimeException(e);
}
return null;
});
}
static Request.Builder getRequestBuilder() {
String agent = String.format("ConvertAPI-Java/%.1f (%s)", 1.6, System.getProperty("os.name"));
return new Request.Builder().header("User-Agent", agent);
}
static RemoteUploadResponse remoteUpload(String urlToFile, Config config) {
HttpUrl url = Http.getUrlBuilder(config)
.addPathSegment("upload-from-url")
.addQueryParameter("url", urlToFile)
.build();
Request request = Http.getRequestBuilder()
.url(url)
.method("POST", RequestBody.create(null, ""))
.addHeader("Accept", "application/json")
.build();
String bodyString;
try {
Response response = Http.getClient().newCall(request).execute();
//noinspection ConstantConditions
bodyString = response.body().string();
if (response.code() != 200) {
throw new ConversionException(bodyString, response.code());
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return new Gson().fromJson(bodyString, RemoteUploadResponse.class);
}
}