0

I have below code.

Content is coming in request which is non english and UTF-8 encoded. How to read it ? Currently i am doing this but looks like it is not correct.

private String readContent(HttpServletRequest request) throws 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;

}

VJS
  • 2,891
  • 7
  • 38
  • 70
  • See https://stackoverflow.com/questions/13350676/how-to-read-write-this-in-utf-8 – Ori Marko Aug 30 '18 at 06:41
  • @user7294900 : I am creating reader like this : reader = request.getReader(); so that i can do reader.readLine(). How to do this using the link you provided – VJS Aug 30 '18 at 06:46
  • This is more specific https://stackoverflow.com/questions/49277027/open-a-bufferedreader-in-utf-8 – Ori Marko Aug 30 '18 at 06:49
  • Didn't get much from this link as well. Appreciate if you can explain with some code, please which i required. – VJS Aug 30 '18 at 06:55
  • 1
    last but not least https://stackoverflow.com/questions/27248208/encoding-utf-8-in-httpservlet-request – Ori Marko Aug 30 '18 at 07:01
  • Possible duplicate of [Encoding UTF-8 in HTTPServlet request](https://stackoverflow.com/questions/27248208/encoding-utf-8-in-httpservlet-request) – Ori Marko Aug 30 '18 at 08:09

1 Answers1

0

I would do something like this and use Apache Commons IOUtils. You just need to specify your encoding.

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

You can use a try /catch block to handle with the IOException that can be thrown. Or let your method throw an Exception that will be catched/handled somewhere else.

iuginga
  • 3
  • 3