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

时间:2016-07-12 00:37:59

标签: java android json spring resttemplate

我搜索了很多,但我没有找到任何解决方案。我试图通过android使用客户端Resttemplate将带有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 [&#34; asBigDecimal&#34;]);嵌套异常是   com.fasterxml.jackson.databind.JsonMappingException:JsonObject   (通过参考链:com.google.gson.JsonObject [&#34; asBigDecimal&#34;])

1 个答案:

答案 0 :(得分:0)

我没有使用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,这不是一个断点线。