Bom dia.
Tenho um sistema em Android que faz consultas em um web service em PHP que retorna as informações utilizando json. O meu problema é quando a string tem algum acento. Sei que o json só trabalho com UTF-8, mas todas as alterações que fiz não da certo. Ou retorna null, ou retorna \u00c3 por exemplo.
Segue meu codigo.
Alguem tem alguma ideia de qual seria o problema?
Obrigado
Codigo em PHP do web service:
<?php
header('Content-type: application/json; charset=utf-8');
ini_set('memory_limit','1536M');
ini_set('max_execution_time','60');
$input = file_get_contents('php://input');
//decodifica os arrays dentro dos arrays
function array_ut8_encode_recursive(&$itm) {
$new = $itm;
if (is_string($new)) return utf8_encode(trim($new));
if (is_array($new)) return array_map('array_ut8_encode_recursive', $new);
if (is_object($new)) foreach (get_object_vars($new) as $key) $new->$key = array_ut8_encode_recursive($new->$key);
return $new;
}
$conteudo = json_decode($input);
//pega os valores q vem do android
$sistema = $conteudo->{'sistema'};
$sql = $conteudo->{'sql'};
$operacao = $conteudo->{'operacao'};
if ($operacao=='consulta'){
//verifica o sistema
if ($sistema == 'mulsis'){
include("../config/global.php");
$res = mssql_query($sql);
};
if(mssql_num_rows($res)) {
while ($post = mssql_fetch_assoc($res))
{
$post2[] = array_ut8_encode_recursive($post);
}
echo json_encode(array('retorno'=>$post2));
};
};
?>
Código em java do aplicativo android.
private JSONArray requisita(Object obj) throws Exception {
BufferedReader bufferedReader = null;
JSONArray message;
try {
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "UTF-8");
params.setBooleanParameter("http.protocol.expect-continue", false);
HttpClient httpclient = new DefaultHttpClient(params);
HttpPost httppost = new HttpPost(url_WS);
StringEntity se = new StringEntity(obj.toString());
httppost.setEntity(se);
System.out.print(se);
HttpResponse response = httpclient.execute(httppost);
bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer stringBuffer = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
Log.d("GetHttp", "Iniciando leitura de buffer.");
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line + NL);
Log.d("GetHttp", stringBuffer.toString());
}
bufferedReader.close();
Log.d("GetHttp", "Leitura de buffer finalizada");
String page = stringBuffer.toString();
JSONObject object = (JSONObject) new JSONTokener(page).nextValue();
message = object.getJSONArray("retorno");
return message;
} catch (Exception e) {
Log.e("GetHttp", e.toString());
return null;
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
Log.e("GetHttp", e.toString());
}
}
}
}