我需要将字符串从Android发送到php Web服务(用户在EditText中输入(。运行正常,带有标准字符和一些特殊字符(如重音符号、ñ 等(,但是当我发送西里尔或阿拉伯语字符时,Web 服务无法识别,并替换为其他字符(如 â±ÐÒ(。这是我的安卓代码:
// Post the data:
public class Sincronizar extends AsyncTask<JSONObject, JSONObject, JSONObject> {
String resFromServer=null;
private String url = "http://.../send.php"; //The url of the web service
@Override
protected JSONObject doInBackground(JSONObject... data) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
JSONObject jsonResponse = null;
try {
JSONObject jsonPlace = new JSONObject();
jsonPlace.put("pais", ((EditText)findViewById(R.id.etTexto)).getText().toString());
JSONArray postjson=new JSONArray();
postjson.put(jsonPlace);
// Post the data:
httppost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
httppost.setHeader("json",jsonPlace.toString());
httppost.getParams().setParameter("jsonpost",postjson);
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
if (response.getEntity()!=null) {
resFromServer = org.apache.http.util.EntityUtils.toString(response.getEntity());
jsonResponse=new JSONObject(resFromServer);
}
} catch (Exception e) {
Log.e("Sincronizar","doIn:"+resFromServer);
}
return jsonResponse;
}
@Override
protected void onPostExecute(JSONObject jsonResponse) {
try{
if (jsonResponse!=null) {
String pais = jsonResponse.getString("pais");
String respuesta = String.format("PAIS: %s",pais);
Log.e("Sincronizar",""+respuesta);
((TextView)findViewById(R.id.textView1)).setText(respuesta);
}
}catch (Exception e) {
Log.e("Sincronizar","onPostExecute: "+e.getMessage());
}
super.onPostExecute(jsonResponse);
}
}
这是php Web服务:
<?php
header('Content-Type: text/html; charset=utf-8');
try {
if (isset($_SERVER['HTTP_JSON'])) {
$json = $_SERVER['HTTP_JSON'];
$cadena = utf8_encode($json);
$data = json_decode($cadena,true);
$json_error= json_last_error();
$pais = $data["pais"];
} else {
$pais="No received";
}
}catch(Exception $e) {
$pais="Exception: ".$e->getMessage();
}
$output=array('pais'=>$pais);
print(utf8_encode(json_encode($output)));
?>
在Web服务中,我还尝试将收到的字符串插入Mysql DB。正常的和一些特殊的字符,如 Ñ、á(重音(等,被接收 e 插入正常。但是对于阿拉伯语或西里尔字符,我会收到这种字符串:"±±","±Ã'À">
我认为问题是编码,但我发送和接收 UTF8(我认为(知道吗?谢谢!
在 php 运行服务器上的 Sql 操作之前
$mysqli->set_charset("utf8")
(或等效的,我使用了mysqli(这解决了我的问题
mysqli_set_charset($con,'utf8');
mysqli_query($con, "insert into table (name, lastname) values ('Ñishá', 'Akopov')");
您可以编写 select 语句并在 utf8 中检索行
希望这会有所帮助
试试这个函数,这可能会对你有所帮助
function parseUtf8ToIso88591($string){
if(!is_null($string)){
$iso88591_1 = utf8_decode($string);
$iso88591_2 = iconv('UTF-8', 'ISO-8859-1', $string);
$string = mb_convert_encoding($string, 'ISO-8859-1', 'UTF-8');
return "";
}
return $string;
}