我使用一个方法根据Locale.getDefault()获取月份的显示名称
private String getLocaleMonthString(Date date){
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return cal.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.getDefault());
我在http请求
中发送此结果,http请求
编码是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;
最佳答案
您可以为 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”。或者 6 月的 Calendar.LONG
和 \u05D9\u05D5\u05E0\u05D9
。
因此,根据其他评论,从日期中获取正确编码的字符没有任何问题,因为 String
不处理编码。您需要检查如何在出站 HTTP 请求中发送该请求,以确保正确处理编码。该代码在您的问题中不可见。
关于java - 日历 getDisplayName 返回 utf-8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30622181/