Android:Compare json data with String - php

I use json to get a string data from php and i want compare this data whit a string ,even when they are equal but returns false for example
php file:
<?php
echo "ok";
?>
java use 3 log
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
page_output = sb.toString();
Log.i("page_output", page_output);
Log.i("page_output", String.valueOf(page_output=="ok"));
Log.i("page_output", String.valueOf(page_output.equals("ok")));
log out
07-12 03:42:45.616: I/page_output(2007): ok
07-12 03:42:45.736: I/page_output(2007): false
07-12 03:42:45.736: I/page_output(2007): false
you can see that page_output is ok but returns false

Try this:
Log.i("page_output", String.valueOf(page_output.trim().equals("ok")));
You are appending "\n" at the end of the every line read from your php response. So you're actually comparing "ok\n" with "ok" and that's why the comparison returns false.
The trim() function removes white spaces, including new lines \n.

in this line:
sb.append(line + "\n");
You add the "\n" new line character to your StringBuilder. When you call toString this character will also be put in your String.
Therefore, page_output.equals("ok\n") will be true.
Or you could just delete the '\n' character from the StringBuilder since I do not see any practical usage in your code

Related

Converting encoded utf-8 JSON

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")

HttpURLConnection is returning garbage from a .php file

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.

String compress in android and send to php server by URL and decompress in php server

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

JsonObject has some extra character

I m using Volley library in android to get JsonObject from my server.
i have create the proper json in server with php
but when i get the json from server it occur a weird problem
i m using json_encode in php to produce json
i dont know what are these extra characters in front of json?
do you know how to solve this problem???
this is a error that i got in android
07-18 20:40:49.151: W/System.err(11636): com.android.volley.ParseError: org.json.JSONException: Value ï»? of type java.lang.String cannot be converted to JSONObject
thanks in advance
I would have posted this as a comment but I wanted to post the relevant code that is in the link. If it works, awesome, if not let me know and I will remove this (as I haven't tested it).
From Skip BOM
"The problem is that your UTF-8 string starts with a byte order mark character (BOM) '0xfeff'. We should fix our JSON parsers to skip this character if it exists.
As a workaround, you can use this code to strip the BOM when you go from InputStream to Reader."
public Reader inputStreamToReader(InputStream in) throws IOException {
in.mark(3);
int byte1 = in.read();
int byte2 = in.read();
if (byte1 == 0xFF && byte2 == 0xFE) {
return new InputStreamReader(in, "UTF-16LE");
} else if (byte1 == 0xFF && byte2 == 0xFF) {
return new InputStreamReader(in, "UTF-16BE");
} else {
int byte3 = in.read();
if (byte1 == 0xEF && byte2 == 0xBB && byte3 == 0xBF) {
return new InputStreamReader(in, "UTF-8");
} else {
in.reset();
return new InputStreamReader(in);
}
}
}
"Or you can remove the byte order mark from your file!"

Getting response in android from PHP

I am getting response from php to android, see below .php
<?php
$username = $_POST[username];
$password = $_POST[password];
if($username == "himm")
{
if($password == "rangde"){
echo "success" ;
}
else{
echo "passwor is wrong.";
}
}
else
{
echo "fail";
}
?>
i am getting success in logcat window of android. But here in android i have made comparison like below,
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.v("","Result : "+result);
Log.v("","this is Result: "+result.equalsIgnoreCase("success"));
if(result.equals("success")){
Log.v("","Login successfully......");
}
else{
Log.v("","Fail to login......");
}
but in logcat window i see "fail to login" message. Php send response as "success" but which type ?
Here condition of if(result.equals("success")) should be true. Please any body give me idea or suggestions to achieve thies..........thank you in advance
sb.append(line + "\n"); modifies the 'success' to 'success\n' so the if(result.equals("success")){ fails because 'success\n' does not match 'success'.
In your android code, you add a trailing LineFeed to the result you receive from php :
sb.append(line + "\n");
So you actually compare 'success' to 'success\n' which is false.
In addition to previously posted answer (which are correct), I would like to point out that HTTP contains mechanisms to do what you are trying to do.
Http authentication allows you to use standard Http return codes (200 in case of success, 401 in case of authentication failure) and to use existing systems to handle that part (most frameworks will provide such).
It also allows you to separate authentication from the rest of the message you send back from the server, and to compare the authentication status at soon as you receive the headers from the server.

Categories