【问题标题】:Read non english UTF-8 content from HTTP request从 HTTP 请求中读取非英文 UTF-8 内容
【发布时间】:2018-08-30 06:39:18
【问题描述】:

我有以下代码。

请求的内容是非英语和 UTF-8 编码的。怎么读?目前我正在这样做,但看起来它不正确。

private String readContent(HttpServletRequest request) 抛出 IOException {

String body = null;
BufferedReader reader = null;

if (logger.isDebugEnabled()) {
    logger.debug("Inside readContent() ...");
}

try {
    // Read from request
    StringBuilder buffer = new StringBuilder();
    reader = request.getReader();
    String line;
    while ((line = reader.readLine()) != null) {
        buffer.append(line + "\n");
    }

//  if (body != null) {
        body = buffer.toString();
        body.trim();
//  }

} catch (IOException ex) {
    throw ex;
} finally {
    if (reader != null) {
        try {
            reader.close();
        } catch (IOException ex) {
            throw ex;
        }
    }
}

if (logger.isDebugEnabled()) {
    logger.debug("Leaving readContent() ..." + body);
}
return body;

}

【问题讨论】:

标签: java http utf-8 internationalization


【解决方案1】:

我会做这样的事情并使用 Apache Commons IOUtils。您只需要指定您的编码。

InputStream inputStream = request.getInputStream();
String contentAsString = IOUtils.toString(inputStream, "UTF-8"); 

您可以使用 try /catch 块来处理可以抛出的 IOException。或者让您的方法抛出一个异常,该异常将在其他地方被捕获/处理。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-10
    • 1970-01-01
    • 2013-05-16
    • 2022-08-12
    • 2012-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多