I'm using this PHP code to generate the JSON from MySQL database:
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = array_map('utf8_encode', $row);
}
echo json_encode($emparray);
Then I use the HttpUrlConnection to fetch the url and get the Echo string:
URL url = new URL("http://localhost/myserver.php");
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
the print is:
[{"id":"1","titulo":"C\u00f3digo de Defesa do Consumidor","descricao":"Institui o c\u00f3digo de defesa do consumidor","tags":"cdc","categorias":"cat_cod,cat_leisord","numero_da_lei":"13105","data_da_lei":"11111111","ativa":"1","byuser":"0","versao_da_lei":"0","url":"http:\/\/www.planalto.gov.br\/ccivil_03\/leis\/L8078compilado.htm"}]
I know that the output is encoded because I have $emparray[] = array_map('utf8_encode', $row); but if I do not use this, the text that has special chars becomes NULL.
How can I convert
"titulo":"C\u00f3digo de Defesa do Consumidor"
to
"titulo":"Código de Defesa do Consumidor"
I've tried:
new String(result.getBytes(), "UTF-8");
but nothing changed
You can use StringEscapeUtils Apache Library https://commons.apache.org/proper/commons-lang/download_lang.cgi
For saving the unicodes in database you have to encode them. So send your unicodes to server by encoding like
StringEscapeUtils.escapeJava("Código de Defesa do Consumidor")
For displaying the encoded unicode in android
StringEscapeUtils.unescapeJava("C\u00f3digo de Defesa do Consumidor")
Related
I have been trying to get JSON data from a .php file. which is returning garbage value. But if I put the url in browser it is showing me the json data perfectly. Here is the code snippet
String authString = username + ":" + password;
byte[] authEncBytes = Base64.encode(authString.getBytes(),0);
String authStringEnc = new String(authEncBytes);
URL url = new URL(urlString);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestProperty("Content-type", "application/json");
httpConn.setRequestProperty("Authorization", "Basic " + authStringEnc);
httpConn.setRequestMethod("GET");
httpConn.connect();
InputStream stream = httpConn.getInputStream();
And for converting it from input stream to string
public static String convertinputStreamToString(InputStream ists)
throws IOException {
if (ists != null) {
StringBuilder sb = new StringBuilder();
String line;
try {
BufferedReader r1 = new BufferedReader(new InputStreamReader(
ists, "UTF-8"));
while ((line = r1.readLine()) != null) {
sb.append(line).append("\n");
}
} finally {
ists.close();
}
return sb.toString();
} else {
return "";
}
}
PROIBLEM is this if I bring "sb" it returns weird garbage value. seems like js code like the following
function toNumbers(d){var e=[];d.replace(/(..)/g,function(d){e.push(parseInt(d,16))});return e}function toHex(){for(var d=[],d=1==arguments.length&&arguments[0].constructor==Array?arguments[0]:arguments,e="",f=0;fd[f]?"0":"")+d[f].toString(16);return e.toLowerCase()}var a=toNumbers("f655ba9d09a112d4968c63579db590b4"),b=toNumbers("98344c2eee86c3994890592585b49f80"),c=toNumbers("72355c05897edf080a57d7f54b23a51e");document.cookie="__test="+toHex(slowAES.decrypt(c,2,a,b))+"; expires=Thu, 31-Dec-37 23:55:55 GMT; path=/"; document.cookie="referrer="+escape(document.referrer); location.href="http://emgcall.byethost9.com/getData.php?ckattempt=1";This site requires Javascript to work, please enable Javascript in your browser or use a browser with Javascript support
I have tried set content to Application/Json in my php file. same result.
What is the problem and solution might be.
Here is the php code
<?php
header('Content-type: application/json');
function x(){
$con=mysqli_connect("com","","","");
if (mysqli_connect_errno($con)){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM emgCall";
$result = mysqli_query($con,$sql);
if (mysqli_num_rows($result) > 0) {
$response["numbers"] = array();
while($row = mysqli_fetch_assoc($result)){
$number = array();
$number['id']=$row['id'];
$number['number']=$row['number'];
$number['image']=base64_encode($row['image']);
array_push($response["numbers"], $number);
}
$son=json_encode($response);
mysqli_close($con);
return $son;
} else {
$outputs["success"] = 0;
$outputs["message"] = "No products found";
}
}
echo $data = x();
?>
At first you need to check where from these html response coming from.
I already checked it and for each request it return an html response which contains a redirect url. It's working on browser, because browser automatically render this html response and then redirect to the url.
You can also check it by yourself: goto this site: http://requestmaker.com/ and place this url : http://emgcall.byethost9.com/getData.php?ckattempt=1 and make a get request. You can then observe the actual response from your code.
So, please check if there is any module or service added to php server that automatically added some cookies/auth-data and then force browser to redirect.
I'm assuming that your url is : http://emgcall.byethost9.com/getData.php?ckattempt=1
Thanks.
I am trying to send compress string message by android device to PHP server.
This is my android code
ByteArrayOutputStream os = new ByteArrayOutputStream(string.length());
GZIPOutputStream gos = new GZIPOutputStream(os);
gos.write(string.getBytes());
gos.close();
byte[] compressed = os.toByteArray();
os.close();
and this is my php code to decode
$msg=$_GET['MsgType'];
$msg2=urldecode($msg);
print gzuncompress($msg2);
but there is error
Message: gzuncompress(): data error
i searched alot on google but didn't help if any one could help me most welcome.
You should use a post variable because url's lenght is limited to few KBs...!
You should use the following code to compress the String
public static String compressAndSend(String str, String url) throws IOException {
String body1 = str;
URL url1 = new URL(url);
URLConnection conn1 = url1.openConnection();
conn1.setDoOutput(true);
conn1.setRequestProperty("Content-encoding", "gzip");
conn1.setRequestProperty("Content-type", "application/octet-stream");
GZIPOutputStream dos1 = new GZIPOutputStream(conn1.getOutputStream());
dos1.write(body1.getBytes());
dos1.flush();
dos1.close();
BufferedReader in1 = new BufferedReader(new InputStreamReader(
conn1.getInputStream()));
String decodedString1 = "";
while ((decodedString1 = in1.readLine()) != null) {
Log.e("dump",decodedString1);
}
in1.close();
}
On PHP side use this,
<?php echo substr($HTTP_RAW_POST_DATA,10,-8); ?>
And please concern this Help manual for more information,
http://php.net/manual/en/function.gzuncompress.php
I am fetching data from a php server in its normal format..the columns are details and image..
I want the image in base64 format nd the details in utf8 format..all this data into one array that will be json encoded and will then be parsed at android side..How do i do this..so that i can Json parse in this manner..
String result= convertStreamToString(is);
JSONObject json=new JSONObject(result);
jArray=json.getJSONArray("details");
for(int i=0;i<jArray.length();i++)
{
JSONObject c=jArray.getJSONObject(i);
String detail=c.getString("details");
String image=c.getString("image");
Log.v("topics", topic);
is.close();
}
The php code:
while($out=mysql_fetch_assoc($result))
{
echo $out;
print_r(base64_encode($out[image]));
echo base64_encode($out['image']);
echo utf8_encode($out['details']);
$tempImage = base64_encode($out['image']);
echo $tempImage;
$tempDetails = utf8_encode($out['details']);
$post[] = array("image"=>$tempImage);
$post []= array("details"=>$tempDetails);
}
echo json_encode(array("login"=>$post));
i think that you can use this link to learn about this
Issues-parsing data to the php and jsons
or visit this : http://androidexample.com/JSON_Parsing_-_Android_Example/index.php?view=article_discription&aid=71&aaid=95
I am developing an application in which I am getting data from web service and displaying in the Android mobile. But the problem is while getting Turkish data it is not displaying correctly.
I already set utf-8 in PHP. But still getting special character symbols like A?ık ?ğ for the string Açık Öğretim.
Here is my PHP code:
<?php
include("Netbrut_class.php");
header('Content-type: text/xml; charset: utf-8');
$webservice = new Netbrut;
$content='<?xml version="1.0" encoding="utf-8"?><salary_comparision>';
$education = $webservice->select_education();
for($i=0; $i<count($education); $i++){
$string = html_entity_decode($education[$i]['comparision_name'], ENT_QUOTES, "utf-8");
$content.="<education id='".$education[$i]['id']."'>".$string."</education>";
}
$content .='</salary_comparision>';
echo $content;
?>
And my Java code is / Here I am writing java code just for testing:
public class testing {
static String[] attributes;
public static void main(String[] args)
{
URL url;
try {
url = new URL("http://192.168.1.106/netBrut/webservices/testing.php");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection = (HttpURLConnection) url.openConnection();
java.io.InputStream is = connection.getInputStream();
InputStreamReader reader = new InputStreamReader(is, "utf-8");
StringWriter sw = new StringWriter();
char [] buffer = new char[1024 * 8];
int count ;
while( (count = reader.read(buffer)) != -1){
sw.write(buffer, 0, count);
}
System.out.println(sw.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
And returning XML from web service is:
<?xml version="1.0" encoding="utf-8"?>
<salary_comparision>
<education id='128'>A?ık ?ğretim</education>//Check here
<education id='5'>Doktora</education>
<education id='3'>Master</education>
<education id='4'>MBA</education>
<education id='2'>?niversite</education>
</salary_comparision>
In the Php code just change the below lines
$string = html_entity_decode($education[$i]['comparision_name'], ENT_QUOTES, "utf-8");
$content.="<education id='".$education[$i]['id']."'>".$string."</education>";
to
$string = $webservice->unhtmlspecialchars($education[$i]['comparision_name']);
$content.="<education id='".$education[$i]['id']."'>".$string."</education>";
See htmlspecialcharsDocs.
I am trying to execute query on database in the localhost and send the JSON object to the client in android. I m not been able to know what is the problem in my code. So some one please help me on this regard.
My php code is the one where i m sending the JSON object.
php code
query executed successfully..
$row=mysql_fetch_array($result1);
$email=$row['EM'];
$pass=$row['PASS'];
$post=array("email"=>$email, "pass"=>$pass);
$posts[] = array("post"=>$post);
//echo "SUCCESS";
header('Content-type: application/json');
echo json_encode(array("posts"=>$posts));
And in android side i ve this code below;
HttpResponse response = doPost(url, kvPairs);
String responseBody=response.toString();
String temp = EntityUtils.toString(response.getEntity());
if (temp.compareTo("SUCCESS")==0)
{
Toast.makeText(this, "Working", Toast.LENGTH_LONG).show();
}
Above part executes ..
Below code throws a JSON exception
JSONObject json = new JSONObject(responseBody);
JSONArray jArray = json.getJSONArray("posts");
no_of_obj=jArray.length();
nemail=new String[no_of_obj];
npass=new String[no_of_obj];
for (int i = 0; i < jArray.length(); i++) {
JSONObject e = jArray.getJSONObject(i);
String s = e.getString("post");
JSONObject jObject = new JSONObject(s);
Toast.makeText(context,jObject.getString("email")+":"+jObject.getString("pass") , duration).show();
nemail[i]=jObject.getString("email");
npass[i]=jObject.getString("pass");
}
In the log cat i can see : The json string must begin with "{"....
Probably you cannot do this
String s = e.getString("post");
because there is no "post" key in the array of Strings you have given,...
Try doing this,
String s = e.has("post")?e.getString("post"):null;
and then on next line keep a null check before Creating JSONObject..
Try this
$posts['data'] = $post;
//echo "SUCCESS";
header('Content-type: application/json');
echo json_encode($posts);