This is how normally we retrieve raw data from server with httppost or get.
This is one of the tutorial from google search
Tutorial link
use a HttpPost to get the data,
convert response to string parse
JSON data, and use it as you want
But what if i want retrieve data and together with related image into my android apps?What is the appropriate method to go for?
This is example of my data.
id image_name caption
1 01.jpg Abcd
and my image store in somewhere of my server.
upload/background_image/01.jpg
Convert the image in base64 string in the server side, and retrieve it from the application.
then use the following to decode the base64 string into bitmap
public static String encodeTobase64(Bitmap image)
{
Bitmap immagex=image;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
immagex.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
String imageEncoded = Base64.encodeToString(b,Base64.DEFAULT);
// Log.e("LOOK", imageEncoded);
return imageEncoded;
}
public static Bitmap decodeBase64(String input)
{
byte[] decodedByte = Base64.decode(input, 0);
return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length);
}
you can response them as url, and when you need the image content, issue another request.
or
you can read the image content, base64_encode it and response as string
Related
I'm trying to send data from a VB.NET Application to a php application, i found this code:
Private Function SendRequest(uri As Uri, jsonDataBytes As Byte(),contentType As String, method As String) As String
Dim req As WebRequest = WebRequest.Create(uri)
req.ContentType = contentType
req.Method = method
req.ContentLength = jsonDataBytes.Length
Dim stream = req.GetRequestStream()
stream.Write(jsonDataBytes, 0, jsonDataBytes.Length)
stream.Close()
Dim response = req.GetResponse().GetResponseStream()
Dim reader As New StreamReader(response)
Dim res = reader.ReadToEnd()
reader.Close()
response.Close()
Return res
End Function
Dim data = Encoding.UTF8.GetBytes(jsonSring)
Dim result_post = SendRequest(uri, data, "application/json", "POST")
at: source
But I can't get the posted data on php. It sends the headers, but the data no.
So, I need help to figure it out what is missing.
I also had same issue and got solution from comments only. As you are passing binary data then in php you need to read binary data as raw input
To get the Raw Post Data:
<?php $postdata = file_get_contents("php://input"); ?>
I have an android application, that makes a connection to a PHP-script, which then fetches data from a database and returns the result. It all works fine and dandy, except for language-settings. I have set the language to dainsh and UTF-8, all the places I can think of, and when I send it to the database it is in danish, but the returnvalue is not in danish.
Here is my call to the PHP-script from android
URL url = new URL(selectUrl);
HttpURLConnection httpUrlConncetion = (HttpURLConnection) url.openConnection();
httpUrlConncetion.setRequestMethod("POST");
httpUrlConncetion.setDoInput(true);
httpUrlConncetion.setConnectTimeout(10000);
httpUrlConncetion.setRequestProperty("Accept-Language", "da_DK");
httpUrlConncetion.setRequestProperty("Content-type", "application/json");
httpUrlConncetion.connect();
String line = "";
StringBuilder sb = new StringBuilder();
int Httpresult = httpUrlConncetion.getResponseCode();
Log.d(TAG, httpUrlConncetion.getResponseMessage().toString());
if (Httpresult == HttpURLConnection.HTTP_OK) {
InputStream inputStream = httpUrlConncetion.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
while ((line = reader.readLine()) != null) {
sb.append(line);
list.add(line);
}
result=sb.toString();
for(int i=0;i<list.size();i++){
Log.d(TAG, "min nye list" + list.get(i) + "\n");
}
and the Logcat says
it is ,"minegen":"n\u00f8gler"} that is the problem. it should have been the danish "nøgler".
The php has been set like this in the connection-file to the database:
"mysqli_set_charset($con, "utf8");
and the mysqli-database has been set to danish language - like this
And I do get danish characters in the table when checking in the table
So what am I missing??
Any help would be highly appreciated :)
I once run into a issue like this it was about saving emojis like you i had all charset set correctly but no matter what i did it didn't work so finaly i end up using urlencode($content) when saving into my database and urldecode($content) when retrieving data
I had a problem like this for Persian characters and I solved it by bad way which worked for me. I just defined my own encoding and made two functions FAtoEN(s) and ENtoFA(s). FAtoEN changes each Persian char to an English char using keyboard keys. for example changes "ن" to "k" because I use k key on keyboard when the keyboard is persian and I want to write ن. and also the other function do this inverse.
byte[] data = Base64.decode(jsonChildNode.optString("profilePicture"),Base64.DEFAULT);
String profilePicture = new String(data,"UTF-8");
My php encode:
$row1['profilePicture'] = base64_encode($row1['profilePicture']);
The output from Android is: ???JFIF????...
It's not displaying the picture.
You are loading the image as string and not processing it back to binary.
ImageView imgViewer = (ImageView) findViewById(id.of.your.img_viewer);
Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length);
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
imgViewer.setMinimumHeight(dm.heightPixels);
imgViewer.setMinimumWidth(dm.widthPixels);
imgViewer.setImageBitmap(bm);
As you can see, in this example the data in byte array is loaded to a Bitmap object so that you can get the image representation.
I am new to JSON. KIndly help me with the JSON parsing in php sent from android.
I have a class A, having members phoneNumber and name. I have an arrayList of object A
private ArrayList<A> contactList = new ArrayList<A>();
contactList.add(a1);
contactList.add(a2); [objects of A]
Now I am trying to send this arrayList to php server using JSON.
JSONObject json = new JSONObject();
json.put("contactList", contactList);
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("");
StringEntity se = new StringEntity("JSON: " + json.toString());
post.setEntity(se);
HttpResponse resP = client.execute(post);
Please let me know how to I parse it in the php server side to get phoneNumber and name of each object A.
I tried to create a same class A in the php server side and trying this way.
<?php
$contactList = array();
if(isset($_POST["contactList"])) {
$contactList = json_decode($_POST["contactList"]);
include_once './eachContactClass.php';
foreach ($contactList->contactList as $eachContact) {
$eachObj = new eachContactClass();
$eachObj = $eachContact;
$name = $eachObj->getName();
$phoneNumber = $eachObj->getPhone();
}
}
Please let me know whether the approach is correct, or kindly help me to correct it
First of all, may I suggest you to use a library for handling the JSON serialization/deserialization. GSON would be suited for your work.
Then, you should check the result JSON for validity before sending it to any remote server.
To parse it in PHP, use the json_decode() function that will return your an object representing your JSON. You can also get a hash if you prefer, just look in the doc.
I think your problem is that your JSON is invalid, as the JSONObject doesn't correctly serialize your ArrayList. Your should probably check that.
Sending a image to mysql using android, json and php
I was able to get my bitmap converted to a properly formatted string using
converting-images-to-json-objects
Here is the code in android
JSONObject values = new JSONObject();
values.put(KEY_CONTRACTUUID, con.UUID);
...
if (con._sig != null) {
String encodedImage = getStringFromBitmap(con._sig);
values.put(KEY_CONTRACTSIGIMAGE, encodedImage);
private static String getStringFromBitmap(Bitmap bitmapPicture) {
/*
* This functions converts Bitmap picture to a string which can be
* JSONified.
*/
final int COMPRESSION_QUALITY = 100;
String encodedImage;
ByteArrayOutputStream byteArrayBitmapStream = new ByteArrayOutputStream();
bitmapPicture.compress(Bitmap.CompressFormat.PNG, COMPRESSION_QUALITY,
byteArrayBitmapStream);
byte[] b = byteArrayBitmapStream.toByteArray();
encodedImage = Base64.encodeToString(b, Base64.DEFAULT);
return encodedImage;
}
now that it is in base64 and a string I need to retrieve it properly to place in my BLOB in mysql
I am not using namevalue pairs or any of that nonsense - simply send it as json and get the json string like so:
$json = json_decode($HTTP_RAW_POST_DATA,true);
echo var_dump(HTTP_RAW_POST_DATA);
...
$varsigimage = $json['sigimage'];
$formatedJSONimage = "{'sigimage': '$varsigimage'}";
var_dump($formatedJSONimage);
$sigImagedecoded = json_decode($formatedJSONimage);
var_dump($sigImagedecoded);
i need to call json_decode on the image to get it out of 64bit to place in the blob correct?
However to do this I need to use the function json_decode, but json_decode assumes I will give it a JSONObject, and since I have many more objects in my $json object, i need to recreate a single JSON object with just the image inside of it, and pass that to the json_decode
but it retuns json_error of type SYNTAX
What am I doing wrong, What is the correct approach of converting the base64 string to a blob?
and yes, I am going to have the same question on getting it out of the blob back to a base64 string
json_decode parses a JSON string and returns an associative array, mimicking the key/value pairs in the JSON string.
It seems like you are missing another step: you need to decode the base64-encoded image string back to a bitmap. e.g. in your code:
$json = json_decode($HTTP_RAW_POST_DATA,true);
echo var_dump(HTTP_RAW_POST_DATA);
...
$varsigimage = $json['sigimage'];
$image_bitmap = base64_decode($varsigimage); // decode the string back to binary
You should now be able to save $image_bitmap as a BLOB in your database.