Reputation: 135
I'm developing android app with backend, both in Java, and communicating through Http Post.
When I'm sending request that contains non-english characters, the backend gets them fine, but when the backend trying to return non-english characters, they receive as '?'.
Say I'm sending as parmas "STR=שלום עולם"
(Hebrew characters)
Backend sample servlet:
public class DebugServlet extends HttpServlet {
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
String param = req.getParameter("STR");
log(param); //Prints שלום עולם, So receiving fine!
try(PrintWriter out = resp.getWriter()) {
out.print(param);
}
}
}
Client code:
private final static String CHARSET = "UTF-8";
public static void send(String server, String servletName, Map<String, String> params){
try{
URL url = new URL(server + servletName);
URLConnection connection = url.openConnection();
HttpURLConnection conn = (HttpURLConnection) connection;
OutputStream os;
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
conn.setRequestMethod("POST");
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
os = conn.getOutputStream();
//Add parameters
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, CHARSET));
StringBuilder paramsSB = new StringBuilder();
boolean isFirst = true;
for(Map.Entry<String,String> entry : params.entrySet()){
if(isFirst)
isFirst = false;
else
paramsSB.append("&");
paramsSB.append(URLEncoder.encode(entry.getKey(), CHARSET));
paramsSB.append("=");
paramsSB.append(URLEncoder.encode(entry.getValue(), CHARSET));
}
writer.append(paramsSB.toString());
writer.flush();
writer.close();
os.close();
int responseCode;
responseCode = conn.getResponseCode();
if (responseCode != 200)
throw new RuntimeException("...");
StringBuilder chain = new StringBuilder("");
try(BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
String line = "";
while ((line = rd.readLine()) != null) {
chain.append(line);
}
}
Log.d("MyTAG", chain.toString()); //Prints "???? ????", that's the problem
} catch (IOException e) {
// writing exception to log
throw new RuntimeException("...");
}
}
Thanks :)
Upvotes: 0
Views: 798
Reputation: 9665
You need to set response encoding UTF-8 for HttpServletResponse. Default encoding is ISO_8859_1
// response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8";
// Write utf-8 strings
Upvotes: 2