标题说明了一切,我需要发送一张照片从我的手机到一个外部api,是期待一个字符串包含照片。这个字符串应该是照片的字节。我该如何实现这一点?
我曾尝试使用Refrofit连接到api,但无法将字节数组转换为单个字符串。
这是我现在的代码:
@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();
}
暂无答案!
目前还没有任何答案,快来回答吧!