我再次需要你的帮助。我想将特殊字符从Android应用程序发送到PHP脚本,反之亦然。
安卓代码
...
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://www.mypage.com/script.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("value", "Español"));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpURLConnection.HTTP_OK){
InputStream inps = response.getEntity().getContent();
InputStreamReader inp = new InputStreamReader(inps, Charset.forName("ISO-8859-2"));
BufferedReader rd = new BufferedReader(inp);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while ((bufferedStrChunk = rd.readLine()) != null) {
stringBuilder.append(bufferedStrChunk);
}
Result = stringBuilder.toString();
}...
PHP代码
<?php
header("Content-Type: text/plain;charset=ISO-8859-2");
echo $_POST["value"];
?>
第一步
我正在尝试将字符串"Español"从Android发送到PHP。我将字符串存储到MySQL表(UNICODE字符集)中,并正确地获得字符串。我还得到了每个烧焦器的整数值。结果是"Español"answers"69.115.112.97.241.111.108"。因此,Android将字符"ñ"发送为241,在UNICODE图表中定义为"ń"。请访问查看http://www.ssec.wisc.edu/~tomw/java/unicode.html#x080
第二步
我将字符串从PHP返回到Android,而不是得到"ñ",而是得到"ń"。这就是我迷失的地方。这种情况什么时候发生变化?为什么具有相同的数值,它们不同?这对我来说太过分了,我请求你的帮助。提前感谢!
在创建发送的URLEncodedEntity
时使用ISO-8859-2。您可以在构造函数中将其设置为参数。
如果没有指定的字符集,您可能会以UTF-8/UTF-16(最常见)发送数据,服务器会以不同的方式对其进行解释。
EDIT:看起来ISO-8859-2不支持ñ。您可能需要在服务器端更改某些内容。http://en.wikipedia.org/wiki/ISO/IEC_8859-2
OK。这是我的最后一段代码,它很有效。我必须指定我的环境:API 15,Android 4.0.3
JAVA代码
...
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://www.mypage.com/script.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("value", "Español"));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs, "ISO-8859-2"));
HttpResponse response = client.execute(post);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpURLConnection.HTTP_OK){
InputStream inps = response.getEntity().getContent();
InputStreamReader inp = new InputStreamReader(inps, Charset.forName("UTF-8"));
BufferedReader rd = new BufferedReader(inp);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while ((bufferedStrChunk = rd.readLine()) != null) {
stringBuilder.append(bufferedStrChunk);
}
Result = stringBuilder.toString();
}
...
PHP代码
<?php
header("Content-Type: text/plain;charset=UTF-8");
echo utf8_encode($_POST["value"]);
?>
有了这段代码,我可以将该字符串发送到PHP脚本,将其存储在数据库中和/或返回到Android应用程序(并在发送时接收)我已经在这方面工作了几天,我希望它能对其他安卓开发者有用。顺便说一下,我在doInBackground()函数中的异步类中使用Java代码。
谢谢,再见