Android RestTemplate使用utf-8发布multipart / form-data

时间:2016-03-07 14:09:03

标签: java android utf-8 multipartform-data resttemplate

我在使用Android的utf-8内容发布multipart / form-data时遇到问题。

这是我的AsyncTask中用于将数据发布到服务器的片段。除了utf字符串数据外,一切正常。服务器收到“????????” <问号而不是utf-8文本。

RestTemplate restTemplate = new RestTemplate();
FormHttpMessageConverter formConverter = new FormHttpMessageConverter();
//formConverter.setCharset(Charset.forName("UTF8")); // don't works

restTemplate.getMessageConverters().add(formConverter);
restTemplate.getMessageConverters().add(new MappingJacksonHttpMessageConverter());
restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());

HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add("Cookie", "my cookie string");

// don't works
//Charset charset = Charset.forName("UTF8");
//ArrayList<Charset> acceptCharset = new ArrayList<>();
//acceptCharset.add(charset);
//httpHeaders.setAcceptCharset(acceptCharset);

File f = new File(this.caller.mainActivity.getApplicationContext().getCacheDir(), "picture");
f.createNewFile();

OutputStream os = new BufferedOutputStream(new FileOutputStream(f));
caller.mainActivity.capturedBitmap.compress(Bitmap.CompressFormat.PNG, 90, os);
os.close();

MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
map.add("picture", new FileSystemResource(f.getPath()));
map.add("categoryId", "1");
map.add("description", "text with utf-8 content ტესტ . test");

HttpEntity<MultiValueMap<String, Object>> requestDataEntity = new HttpEntity<>(map, httpHeaders);

HttpEntity<HashMap> response = restTemplate.exchange("url.of.server", HttpMethod.POST, requestDataEntity, HashMap.class);

服务器没问题。我从postman测试它,服务器可以接收utf-8内容的multipart / form-data。

“描述”的服务器值

是:“带有utf-8内容的文本????。test”

服务器端 - 路径片段

var express = require('express');

var multer  = require('multer');
var upload = multer({ limits: { fileSize: 2000000, files: 1 }, dest: 'tempFiles/' });

....
....

router.post('/add', app.filters.commons.sessionRequired(),  upload.single('picture'), function (req, res, next) {
    activityBL.add(req, function (error, data) {
        error ? next(error) : res.json(data);
    });
});

....
....

activityBL - 业务逻辑的片段

....
....

bl.add = function (req, cb) {

    var file = req.file || null;

    if(!file) {
        cb({errors: [{code: "004", keyword: "PICTURE_REQUIRED"}]}, null);
        return;
    }

    /*
     * retrieve request data
     */
    var requestData = JSON.parse(JSON.stringify(req.body));

    var desc = requestData.description;

    ....
    ....
    ....  
}

1 个答案:

答案 0 :(得分:0)

可能需要设置标题才能显示utf-8字符。

  

标题(&#34; Content-Type&#34;,&#34; application / json; charset = utf-8&#34;);

请参考此链接:http://expressjs.com/en/api.html您会给出更好的主意吗?

确保您获取的表和数据库也应用UTF-8排序规则。

祝你好运.. !!