有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

返回utf8的java Calendar getDisplayName

我使用一种方法根据Locale.getDefault()获取一个月的显示名称

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;

共 (1) 个答案

  1. # 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”。或{}及{}六月{}

    因此,根据其他注释,从日期获取正确编码的字符没有什么错,因为String不处理编码。您需要检查如何在出站HTTP请求中发送此消息,以确保在那里正确处理编码。该代码在您的问题中不可见