I want to utilize https://api.imgbb.com/1/upload in order to upload Bitmaps onto ImageBB using HttpURLConnection as follows:
Upload an image:
public JsonObject uploadImage(Bitmap bitmap) throws IOException, ExecutionException, InterruptedException {
JsonObject JSONInput = new JsonObject();
JSONInput.addProperty(
"image", BASE_64_IMAGE_STRING
);
JsonObject response = new Requests().execute(JSONInput).get();
return response;
}
Requests Class:
public class Requests extends AsyncTask<JsonObject, JsonObject, JsonObject> {
@Override
protected JsonObject doInBackground(JsonObject... jsonObjects) {
URL url = null;
url = new URL("https://api.imgbb.com/1/upload?key=API_KEY&expiration=300");
HttpURLConnection connection = null;
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST")
connection.setRequestProperty("Content-Type", "application/json");
connection.setDoOutput(true);
OutputStream os = connection.getOutputStream()
OutputStreamWriter osw = new OutputStreamWriter(os, StandardCharsets.UTF_8);
osw.write(jsonObjects[0].toString());
osw.flush();
osw.close();
connection.connect()
String result = new BufferedReader(new InputStreamReader(connection.getErrorStream()))
.lines().collect(Collectors.joining("\n"));
StringBuilder response = new StringBuilder();
BufferedReader br = new BufferedReader(
new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonElement jelem = gson.fromJson(response.toString(), JsonElement.class);
return jelem.getAsJsonObject();
}
@Override
protected void onPostExecute(JsonObject jsonObject) {
super.onPostExecute(jsonObject);
}
}
The jsonObjects consists of a single element which is of the form {"image": base64_representation_of_image"}
However, I keep getting {"status_code":400,"error":{"message":"Empty upload source.","code":130},"status_txt":"Bad Request"} back from the API. I can't seem to figure out what I am doing wrong.
I can't find out any resources which use similar APIs in Android. Any direction would be appreciated.
I am trying to use the HttpURLConnection class in order to make API requests to ImageBB. However, it does not seem to recognise the base64 image string I am passing