import java.net.HttpURLConnection;
import java.io.*;
import java.util.UUID;
public class Jimgbb {
public static class Response {
public final int code;
public final String content;
public Response(int code, String content) {
this.code = code;
this.content = content;
}
}
private String apiKey;
public Jimgbb(String apiKey) {
this.apiKey = apiKey;
}
public Response upload(HttpURLConnection conn, InputStream is,
String filename) throws IOException {
return upload(conn, is, filename, null);
}
public Response upload(HttpURLConnection conn, InputStream is,
String filename, String name) throws IOException {
return upload(conn, is, getContentType(filename), filename, name);
}
public Response upload(HttpURLConnection conn, InputStream is,
String contentType, String filename, String name) throws IOException {
String boundary = Long.toHexString(System.currentTimeMillis());
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept", "*/*");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=\"" + boundary + "\"");
try(OutputStream os = conn.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(os, "UTF-8"))) {
writeText(writer, boundary, "key", apiKey);
writeText(writer, boundary, "name", name);
writeFile(writer, boundary, "image", filename, contentType);
copy(is, os);
writer.append("\r\n--" + boundary + "--\r\n").flush();
}
return readResponse(conn);
}
private Response readResponse(HttpURLConnection conn) throws IOException {
int response = conn.getResponseCode();
if (response >= 400) {
try(InputStream is = conn.getErrorStream()) {
return read(is, response);
}
} else {
try(InputStream is = conn.getInputStream()) {
return read(is, response);
}
}
}
private Response read(InputStream is, int response) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
copy(is, bos);
return new Response(response, bos.toString("UTF-8"));
}
private String getContentType(String filename) {
String mimeType = HttpURLConnection.guessContentTypeFromName(filename);
return mimeType == null ? "application/binary" : mimeType;
}
private void writeFile(PrintWriter writer, String boundary,
String fieldName, String filename, String contentType) throws IOException {
writer.append(
"\r\n--" + boundary + "\r\n" +
"Content-Disposition: form-data; name=\"image\"" +
"; filename=\"" + filename + "\"\r\n" +
"Content-Type: " + contentType + "\r\n" +
"Content-Transfer-Encoding: binary\r\n\r\n").flush();
}
private void writeText(PrintWriter writer, String boundary,
String fieldName, String text) throws IOException {
if (text != null) {
writer.append(
"--" + boundary + "\r\n" +
"Content-Disposition: form-data; name=\"" + fieldName + "\"\r\n" +
"Content-Type: text/plain; charset=UTF-8\r\n\r\n" +
text + "\r\n").flush();
}
}
private void copy(InputStream is, OutputStream os) throws IOException {
byte[] buf = new byte[8192];
int n;
while ((n = is.read(buf)) != -1) {
os.write(buf, 0, n);
}
}
}