The title says it all, I need to send a photo taken from my phone to an external API that is expecting a String containing the photo. This string should be the bytes of the photo. How can I implement that?
I've tried using retrofit to connect to the API, but I can't convert the bytes array to a single string.
This is the code I have right now:
@RequiresApi(api = Build.VERSION_CODES.O)
private void analiseIt(Bitmap photo, Context context) {
Uri photoPath = saveToInternalStorage(photo,context);
FileUploadService service = ServiceGenerator.createService(FileUploadService.class);
Call<JsonObject> call = service.upload(toBinary(myBytes));
call.enqueue(new Callback<JsonObject>() {
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
Log.d("Response from server: ", new Gson().toJson(response.body()));
Float reading = Float.valueOf(new Gson().toJson(response.body().get(READING)));
Float accuracy = Float.valueOf(new Gson().toJson(response.body().get(ACCURACY)));
mLastMeasurement = new Measurement(reading, accuracy, new TimeMeasurement(TimeMeasurement.OVERNIGHT_FASTING));
insert(mLastMeasurement);
Log.v("Upload", "success");
}
@Override
public void onFailure(Call<JsonObject> call, Throwable t) {
Log.e("Upload error: ", t.getMessage());
}
});
}
String toBinary( byte[] bytes )
{
StringBuilder sb = new StringBuilder(bytes.length * Byte.SIZE);
for( int i = 0; i < Byte.SIZE * bytes.length; i++ )
sb.append((bytes[i / Byte.SIZE] << i % Byte.SIZE & 0x80) == 0 ? '0' : '1');
return sb.toString();
}
question from:
https://stackoverflow.com/questions/65645492/android-studio-how-can-i-send-a-bitmap-photo-to-api-by-sending-its-bytes-in-a 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…