【发布时间】:2018-10-28 07:23:00
【问题描述】:
我在 Java 中有一个方法,我尝试通过 POST json 请求获取一个整数(用户 ID),这是方法:
public static Integer getUserIdOwnerOfMsg(Message msg) {
Integer idUser = null;
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("textMsg", msg.getTextMsg());
jsonObject.put("hourMsg", msg.getHourMsg());
List list = new LinkedList();
list.addAll(Arrays.asList(jsonObject));
String jsonString = list.toString();
String urlStr = SERVER_PATH + "getUserIdOwnerOfMsgJSON.php";
URL url = new URL(urlStr);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "your user agent");
con.setRequestProperty("Accept-Language", "sp,SP;q=0.5");
//con.setRequestProperty("Content-Type", "text/html; charset=UTF-8");
String urlParameters = "json=" + jsonString;
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
InputStream instream;
int status = con.getResponseCode();
if (status != HttpURLConnection.HTTP_OK)
instream = con.getErrorStream();
else
instream = con.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(instream, "UTF-8")); // ISO-8859-1
in.mark(1);
if(in.read() != 0xFEFF)
in.reset();
String inputLine;
StringBuilder response = new StringBuilder();
while((inputLine = in.readLine()) != null)
response.append(inputLine);
in.close();
JSONObject object = new JSONObject(response.toString());
Boolean correct = object.getBoolean("correct");
if (correct) {
idUser = object.getInt("id");
}
} catch (Exception e) {
e.printStackTrace();
}
return idUser;
}
问题是响应包含一个 UTF-8 BOM 字符,在邮递员上结果没问题,我可以看到 id:({"id":"7","correct":true})
但是在android studio上调试我得到了idUser的值""或null,我不知道为什么,我尝试了很多方法来解决这个问题,但没有成功。
同样在php 服务器端,我执行了echo mb_detect_encoding($idUsuario); 并且得到了ASCII 编码,以防万一有助于找到解决方案。
任何帮助将不胜感激,谢谢!
【问题讨论】:
-
UTF8 永远不需要 BOM,PHP 也不关心编码。您的文本编辑器可能会在打开
<?php之前将其添加到您的一个或多个 PHP 源文件中。
标签: php encoding byte-order-mark