2015-06-03 24 views
0

我用的方法根据Locale.getDefault()日历getDisplayName返回UTF-8

private String getLocaleMonthString(Date date){ 
Calendar cal = Calendar.getInstance(); 
cal.setTime(date); 
return cal.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.getDefault()); 

我在http request发送该结果得到了一个月的显示名称,http request编码为UTF-8

而且显示名称是???对于某些语言,即使在我的日志中它是正确的。

问题是string没有用正确的编码创建,但我没有看到我可以在这一小段代码中更改/设置编码?

编辑:

添加的代码为httppost的要求

Date date = null; 
    HttpPost post = null; 
    MultipartEntityBuilder builder = null; 
    builder = MultipartEntityBuilder.create(); 
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); 
    builder.setCharset(Charset.forName(HTTP.UTF_8)); 
    date = getDateFromFile(file,0); 
    String localeMonth = getLocaleMonthString(date); 
    post = new HttpPost(url); 
    builder.addPart("filePath", new StringBody(file.getAbsolutePath(),ContentType.TEXT_PLAIN)); 
    builder.addPart("date", new StringBody(getISODate(date), ContentType.TEXT_PLAIN)); 
    builder.addPart("localeMonth", new StringBody(localeMonth, ContentType.APPLICATION_FORM_URLENCODED)); 
    builder.addPart("type", new StringBody("video", ContentType.TEXT_PLAIN)); 

    HttpResponse response = null; 
+0

字符串本身没有编码。当字符串中的字符被转换为字节(在HTTP响应中)时,会发生编码。 – Jesper

+0

“对于某些语言,显示名称是??? ......对于哪些语言,哪些字段/样式以及哪些浏览器发生了这种情况? – javabrett

+0

该语言是希伯来语,在Firefox上。田/样式?默认值我猜 –

回答

1

您可以编写单元测试getLocaleMonthString,做一样的东西:

Calendar cal = Calendar.getInstance(); 
cal.setTime(new Date(1433367642000L)); 
assertEquals("\u05D9\u05D5\u05E0", cal.getDisplayName(Calendar.MONTH, Calendar.SHORT, new Locale("he"))); 

...其中1433367642000L现在和\u05D9\u05D5\u05E0יונ或“Jun”。或者Calendar.LONG\u05D9\u05D5\u05E0\u05D9六月יוני

因此,根据其他评论,从日期获取正确编码的字符没有任何问题,因为String s不涉及编码。您需要检查您在出站HTTP请求中如何发送这些信息,以确保在那里正确处理编码。该代码在您的问题中不可见。