gpt4 book ai didi

java - 从 Http Post 接收 UTF-8 响应

转载 作者:行者123 更新时间:2023-12-02 03:15:54 25 4
gpt4 key购买 nike

我正在开发带有后端的 Android 应用程序,都是用 Java 编写的,并通过 Http Post 进行通信。当我发送包含非英语字符的请求时,后端可以很好地获取它们,但是当后端尝试返回非英语字符时,它们会收到“?”。假设我发送为 parmas "STR=שלום עולם" (希伯来语字符)

后端示例 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);
}
}
}

客户端代码:

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("...");
}
}

谢谢:)

最佳答案

您需要为 HttpServletResponse 设置响应编码 UTF-8。默认编码为 ISO_8859_1

    // response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8";

// Write utf-8 strings

关于java - 从 Http Post 接收 UTF-8 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40308691/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com