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!"
Related
I post to server raw byte [] of texture but shows 5B in sql database and when this data is downloaded the file is empty. Can you please provide guidance?
I post to server the raw byte[] of a texture like so:
byte [] imgByte0 = uploadedTex.GetRawTextureData();//uploadTex is Texture2D
Debug.Log("Byte Len " + imgByte0.Length);//results in 722160
WWWForm form = new WWWForm();;
form.AddBinaryData("rgbImgBytes", imgByte0, "image/png");
UnityWebRequest www = UnityWebRequest.Post("https:address.php", form);
yield return www.SendWebRequest();
I post it to my php and insert into sql database BLOB (I'm aware there are other preferred alternatives to store images, imgs are/will be stufficiently small not the question here):
$thisRGBImg=$_FILES['rgbImgBytes'];
$stmt = $conn->prepare("INSERT INTO $imageTable `thisRGBImg` VALUES (?)");
$stmt->execute([$thisRGBImg];
Png image is 300Kb, however it shows as 5B held in sql database BLOB. I further confirm when I download these raw bytes to file (as per https://thoughtbot.com/blog/avoiding-out-of-memory-crashes-on-mobile#streams-to-the-rescue) and resulting file is empty:
using (UnityWebRequest myWebRequest = UnityWebRequest.Post(path, formData2))
{
myWebRequest.downloadHandler = new ToFileDownloadHandler(new byte[64 * 1024], savePathWithFileName);
yield return myWebRequest.SendWebRequest();
}
public ToFileDownloadHandler(byte[] buffer, string filepath) : base(buffer)
{
this.filepath = filepath;
fileStream = new FileStream(filepath, FileMode.Create, FileAccess.Write);
}
protected override bool ReceiveData(byte[] data, int dataLength)
{
if (data == null || data.Length < 1)
{
Debug.Log("ReceiveData - received a null/empty buffer");
return false;
}
received += dataLength;
Debug.Log("Data received " + dataLength + " total received " + received);
//if (!canceled) fileStream.Write(data, 0, dataLength);//replaced for bw below
if (!canceled)
{
var bw = new BinaryWriter(File.Open("path", FileMode.OpenOrCreate));
bw.Write(data);
bw.Flush();
bw.Close();
}
return true;
}
I'm trying to return a value (string) from php to IOS application:
echo "1";
This is the swift code:
let returnedData = NSString(data: unwrappedData, encoding: String.Encoding.utf8.rawValue) as! String
print(returnedData)
if returnedData == "1" {
... something
}
The print function shows the correct value (that is, 1).
But the check fails.
String(...) gives me Optional("1\n\n")
That indicates that the output is followed by two newline characters, as in this
example:
let data = Data(bytes: [0x31, 0x0a, 0x0a])
if let string = String(data: data, encoding: .utf8) {
print(string) // 1
print(string.debugDescription) // "1\n\n"
print(string == "1") // false
}
debugDescription is a very useful method to detect “invisible” string
characters.
The solution is (compare Does swift have a trim method on String?):
let trimmed = string.trimmingCharacters(in: .whitespacesAndNewlines)
print(trimmed == "1") // true
I am trying to send data from MSSQL table on server to Android app via PHP. I am using Volley to send the request for data.
The issue is that no matter what I try, Android says the returned JSON encoded string is "Malformed".
I have put the returned JSON string "response" into online JSON decoders and it displays perfectly, yet Andoid says: "Syntax error, malformed JSON{"data":[{"claimNumber":"f265e5e.....}]".
However, if I hardcode a copy and paste of the returned "response" string into a variable "input" in the Android
response function, it works perfectly.
JSONObject jObj = new JSONObject(response); ** Fails - Android says Malformed.
JSONObject jObj = new JSONObject(input); ** Android uses it with no issues.
The following is the method in Android used to receive the PHP response. Have included Log outputs of both the "response" string and
the manually entered "input" string. They are identical, yet Android won't use the actual "response" string.
public void onResponse(String response) {
if (response.equals("failed")) {
Log.d("failed", "failed");
callback.onResponse(null);
return;
}
try {
// Android sees the response returned from the PHP function as always Malformed.
Log.d("response", response);
D/response: - Syntax error, malformed JSON {"data":[{"claimNumber":"f265e5e6513070abd1f711232cfd3a491075f15bc9714cf723e373f02e71a214","xlsLine":"8b3490231cd923c133989dd93574de131b6c388a86153a74eb6ae2507193a008c9d3d0264452cc1bd1113d5a722f3ea7975f322461f486be96e789424459e20bcbaf878f5d0efe09426b90c046d881100e166ef0bfcf8721266383aabf3837a213854e8425e92b722791640576d3c0ce7722ff3de2e6005c85df840bea3b10982b7bcf8bec3398ea03e08e6a2879cb29e0e6c3c05370e1c2cf819e6156991c762b2247e8a5b51edb852bb371aca011eccaa581ed577e74d6bf0f2a71e43e7751e3fa6e5f68c2a6e4ccd4fc338fc2a2ea4a9d98018c52fe5953741a53d7f7a6f1c1e57901d64c957dc1776ab0ed28f5754f7d44008ebc5864cfd34dd3b1f1bf82db49674b8e7a3e381882f7cc1035bfdba114280f6c173e337d1813fb47a9b1aaf1d52faac197f90cced9eea754cf441cb262b3117444ad3a265cefb9593d40cdb8a3ae0235cc06baffbcac493bf45852908b014f063c29d85347e808e7ed4be8688327bf3280759ea1ff187287dcabaaee8859a6da782cd2451e2911fe16ca7d","markerColor":"0","edited":"0"}]}
// If I copy the returned "response" string manually into a variable "input", Android says it's fine.
String input = "{\"data\":[{\"claimNumber\":\"f265e5e6513070abd1f711232cfd3a491075f15bc9714cf723e373f02e71a214\",\"xlsLine\":\"8b3490231cd923c133989dd93574de131b6c388a86153a74eb6ae2507193a008c9d3d0264452cc1bd1113d5a722f3ea7975f322461f486be96e789424459e20bcbaf878f5d0efe09426b90c046d881100e166ef0bfcf8721266383aabf3837a213854e8425e92b722791640576d3c0ce7722ff3de2e6005c85df840bea3b10982b7bcf8bec3398ea03e08e6a2879cb29e0e6c3c05370e1c2cf819e6156991c762b2247e8a5b51edb852bb371aca011eccaa581ed577e74d6bf0f2a71e43e7751e3fa6e5f68c2a6e4ccd4fc338fc2a2ea4a9d98018c52fe5953741a53d7f7a6f1c1e57901d64c957dc1776ab0ed28f5754f7d44008ebc5864cfd34dd3b1f1bf82db49674b8e7a3e381882f7cc1035bfdba114280f6c173e337d1813fb47a9b1aaf1d52faac197f90cced9eea754cf441cb262b3117444ad3a265cefb9593d40cdb8a3ae0235cc06baffbcac493bf45852908b014f063c29d85347e808e7ed4be8688327bf3280759ea1ff187287dcabaaee8859a6da782cd2451e2911fe16ca7d\",\"markerColor\":\"0\",\"edited\":\"0\"}]}";
// Log showing Androids interpretation of the manually entered "input" string
// It matches the "response" string exactly yet "response" string fails.
Log.d("input", input);
D/input: {"data":[{"claimNumber":"f265e5e6513070abd1f711232cfd3a491075f15bc9714cf723e373f02e71a214","xlsLine":"8b3490231cd923c133989dd93574de131b6c388a86153a74eb6ae2507193a008c9d3d0264452cc1bd1113d5a722f3ea7975f322461f486be96e789424459e20bcbaf878f5d0efe09426b90c046d881100e166ef0bfcf8721266383aabf3837a213854e8425e92b722791640576d3c0ce7722ff3de2e6005c85df840bea3b10982b7bcf8bec3398ea03e08e6a2879cb29e0e6c3c05370e1c2cf819e6156991c762b2247e8a5b51edb852bb371aca011eccaa581ed577e74d6bf0f2a71e43e7751e3fa6e5f68c2a6e4ccd4fc338fc2a2ea4a9d98018c52fe5953741a53d7f7a6f1c1e57901d64c957dc1776ab0ed28f5754f7d44008ebc5864cfd34dd3b1f1bf82db49674b8e7a3e381882f7cc1035bfdba114280f6c173e337d1813fb47a9b1aaf1d52faac197f90cced9eea754cf441cb262b3117444ad3a265cefb9593d40cdb8a3ae0235cc06baffbcac493bf45852908b014f063c29d85347e808e7ed4be8688327bf3280759ea1ff187287dcabaaee8859a6da782cd2451e2911fe16ca7d","markerColor":"0","edited":"0"}]}
JSONObject jObj = new JSONObject(input);
jArray = jObj.getJSONArray("data");
} catch (JSONException e) {
e.printStackTrace();
}
}
// GSON print of JSON Object from the manually entered "input" variable.
I/System.out: {
"nameValuePairs": {
"data": {
"values": [
{
"nameValuePairs": {
"claimNumber": "f265e5e6513070abd1f711232cfd3a491075f15bc9714cf723e373f02e71a214",
"xlsLine": "8b3490231cd923c133989dd93574de131b6c388a86153a74eb6ae2507193a008c9d3d0264452cc1bd1113d5a722f3ea7975f322461f486be96e789424459e20bcbaf878f5d0efe09426b90c046d881100e166ef0bfcf8721266383aabf3837a213854e8425e92b722791640576d3c0ce7722ff3de2e6005c85df840bea3b10982b7bcf8bec3398ea03e08e6a2879cb29e0e6c3c05370e1c2cf819e6156991c762b2247e8a5b51edb852bb371aca011eccaa581ed577e74d6bf0f2a71e43e7751e3fa6e5f68c2a6e4ccd4fc338fc2a2ea4a9d98018c52fe5953741a53d7f7a6f1c1e57901d64c957dc1776ab0ed28f5754f7d44008ebc5864cfd34dd3b1f1bf82db49674b8e7a3e381882f7cc1035bfdba114280f6c173e337d1813fb47a9b1aaf1d52faac197f90cced9eea754cf441cb262b3117444ad3a265cefb9593d40cdb8a3ae0235cc06baffbcac493bf45852908b014f063c29d85347e808e7ed4be8688327bf3280759ea1ff187287dcabaaee8859a6da782cd2451e2911fe16ca7d",
"markerColor": "0",
"edited": "0"
}
}
]
}
}
}
Have tried php output with and without slashes. No change... still malformed.
Have tried stripping non-standard chars. There are none.
Have forced charset "UTF-8". No difference.
Have searched and tried every conceivable solution for this on Google. Nothing works.
I'm at a loss as to what to try next. Totally confused on why Android can't use the returned Json string,
but can use it if you manually take the same string and put it in a variable in the code directly.
Can someone tell me if this is a known bug, if the JSON really is malformed or if something else comes to mind?
Thank you
EDIT
Here is the PHP that creates the json to return to Android.
$options = array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$stmt2 = sqlsrv_query( $conn3, $tsql1, $params, $options);
$row_count = sqlsrv_num_rows($stmt2);
if ($row_count === false) {
echo("failed");
} else {
while( $userClaims = sqlsrv_fetch_array($stmt2, SQLSRV_FETCH_ASSOC) ) {
$claimNum = $userClaims['ClaimNumber'];
$xls = $userClaims['XLS'];
$color = $userClaims['Color'];
$edited = "0";
$keyvals = (object) array("claimNumber" => $claimNum, "xlsLine" => $xls, "markerColor" => $color, "edited" => $edited);
array_push($response,$keyvals);
}
$encoded = json_encode(array('data' => $response));
EDIT 2
The following is the complete php section of code that creates the json return string. The array is initialized at the top. Have written the php json string to a text file on server and copied the text to a json checker and it works fine.
$response = array();
$i = 0;
$param1 = $token;
$params = array( &$param1);
$tsql1 = "SELECT * FROM Claims WHERE Token = ? AND DeletionFlag = 0";
$options = array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$stmt2 = sqlsrv_query( $conn3, $tsql1, $params, $options);
$row_count = sqlsrv_num_rows($stmt2);
if ($row_count === false) {
echo("failed");
} else {
while( $userClaims = sqlsrv_fetch_array($stmt2, SQLSRV_FETCH_ASSOC) ) {
$claimNum = $userClaims['ClaimNumber'];
$xls = $userClaims['XLS'];
$color = $userClaims['Color'];
$edited = "0";
$keyvals = (object) array("claimNumber" => $claimNum, "xlsLine" => $xls, "markerColor" => $color, "edited" => $edited);
array_push($response,$keyvals);
}
$encoded = json_encode(array('data' => $response));
echo $encoded;
}
sqlsrv_close($conn3);
Thank you for your help Andy. I finally figured it out. I found a line of code in the php file that was out of place. It was trying to json_decode an empty string. This is what was generating the extra 36 chars about the malformed string in my actual response. Once I moved it to the correct place, everything started working beautifully. Should have known better, most likely a blasted copy/paste error. Should teach me not to be lazy and actually type ALL my code. Thanks, again!!
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
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.