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 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
| public class HttpWrapper { private static OkHttpClient client = new OkHttpClient();
private static final String DEFAULT_USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36";
public static Builder of(String url) { return new Builder(url); }
public static class Builder {
private String url;
private Map<String, String> params;
private List<MultipartBody.Part> uploadParts;
Request.Builder reqBuilder;
Builder(String url) { this.url = url; params = new HashMap<>(); uploadParts = new ArrayList<>();
reqBuilder = new Request.Builder();
addHeader("User-Agent", DEFAULT_USER_AGENT); }
public Builder addParam(String key, String value) { params.put(key, value); return this; }
public Builder addHeader(String key, String value) { reqBuilder.addHeader(key, value); return this; }
public Builder file(String key, String fileName, String fileMime, byte[] bytes) { MultipartBody.Part part = MultipartBody.Part.createFormData( key, fileName, RequestBody.create(MediaType.parse(fileMime), bytes)); uploadParts.add(part); return this; }
public Builder file(String key, String fileName, String fileMime, File file) { MultipartBody.Part part = MultipartBody.Part.createFormData( key, fileName, RequestBody.create(MediaType.parse(fileMime), file)); uploadParts.add(part); return this; }
public Builder file(String key, String fileName, String fileMime, InputStream stream) throws IOException { int size = stream.available(); byte[] bytes = new byte[size]; stream.read(bytes); return file(key, fileName, fileMime, bytes); }
public Response get() throws IOException { StringBuilder urlBuilder = new StringBuilder(url); if (!params.isEmpty()) { urlBuilder.append("?").append(Joiner.on('&').withKeyValueSeparator('=').join(params)); }
return client.newCall(reqBuilder.url(urlBuilder.toString()).build()).execute(); }
public Response post() throws IOException { FormBody.Builder formBodyBuilder = new FormBody.Builder(); if (!params.isEmpty()) { params.forEach(formBodyBuilder::add); }
return client.newCall(reqBuilder.url(url) .post(formBodyBuilder.build()) .build()) .execute(); }
public Response upload() throws IOException { MultipartBody.Builder bodyBuilder = new MultipartBody.Builder() .setType(MultipartBody.FORM); uploadParts.forEach(bodyBuilder::addPart);
params.forEach(bodyBuilder::addFormDataPart);
return client.newCall(reqBuilder.url(url) .post(bodyBuilder.build()) .build()) .execute(); } } }
|