在 base64 中通过 Android 上的 RestTemplate 发布带有图像的 JSON 时出错



我搜索了很多,但没有找到任何解决方案。我正在尝试使用客户端Resttemplate通过 android 将带有 base64 编码图像的 json 对象发布到 Web 服务。

    RestTemplate restTemplate = new RestTemplate();
    restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
    restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
    ResponseEntity responseEntity;
    try {
        HttpHeaders header = createHeadersAthententicated(accessToken);
        header.setContentType(new MediaType("application", "json"));
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("base64File", ImageUtil.bitmapToString(user.getProfileImageInBitmap()));
        jsonObject.addProperty("filename", "profileImage".concat("_").concat(user.getEmail()));
        HttpEntity<JsonObject> requestEntity = new HttpEntity<>(jsonObject, header);
        responseEntity = restTemplate.exchange(userUrl, HttpMethod.POST, requestEntity, String.class);
    } catch (HttpClientErrorException e) {
        Log.e(TAG, e.getMessage(), e);
        responseEntity = new ResponseEntity(e.getResponseBodyAsString(), HttpStatus.BAD_REQUEST);
    } catch (RestClientException e1) {
        Log.e(TAG, e1.getMessage(), e1);
        responseEntity = new ResponseEntity(e1.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }

public static String bitmapToString(Bitmap bitmap) {
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        byte[] b = baos.toByteArray();
        String temp = Base64.encodeToString(b, Base64.DEFAULT);
        return temp;
    } catch (NullPointerException e) {
        return null;
    } catch (OutOfMemoryError e) {
        return null;
    }
}

我得到的错误:

org.springframework.http.converter.HttpMessageNotWritableException: 无法写入 JSON:JsonObject(通过引用链: com.google.gson.JsonObject["asBigDecimal"]);嵌套异常是 com.fasterxml.jackson.databind.JsonMappingException: JsonObject (通过参考链:com.google.gson.JsonObject["asBigDecimal"])

我在 Resttemplate 上没有进展,所以我改成了 OkHttp3

 final okhttp3.MediaType JSON = okhttp3.MediaType.parse("application/json");
    OkHttpClient client = new OkHttpClient();
    RequestBody body = RequestBody.create(JSON, jsonObject.toString());
    Request request = new Request.Builder()
            .addHeader("Authorization", "Bearer" + accessToken)
            .url(userUrl)
            .post(body)
            .build();

完美工作。

当您转换为base64时,您必须使用Base64.NO_WRAP,这不会放置中断线。

最新更新