gzip compression in android app as client and php server - php

In my android app i want to send compressed data to php server using gzip compression and receive response from the server and decompress the response if it is compressed. But when i am sending compressed data,server is getting null and not the data which i am sending and it is returning error message.
This is code i am using for compression--
public static String compress(String strData) throws Exception
{
ByteArrayOutputStream obj = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(obj);
gzip.write(strData.getBytes("UTF-8"));
gzip.close();
String outStr = obj.toString("UTF-8");
return outStr;
}
This is the code used for decomprssion---
public static String decompress(String str) throws Exception
{
byte[] bytes1 = str.getBytes("UTF-8");
GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(bytes1));
BufferedReader bf = new BufferedReader(new InputStreamReader(gis, "UTF-8"));
String outStr = "";
String line;
while ((line=bf.readLine())!=null) {
outStr += line;
}
return outStr;
}
And I also add a header to httppost request
httpPost.addHeader("Accept-Encoding", "gzip, deflate");
can anyone please tell me what to do if I want to compress data before sending to server and also receive response and decompress it, if it is compressed.

public static void main() {
String myString = "H4sIAAAAAAAAA5WMuwrCMBSGX0XOnCFpLoZ0ExH0FaTDyU0DTVsSB6H03Y3dHN3+67fCgm8wjAA6dz2DASmjUsjRCs8tahu5FCw6DQQmzKEt";
byte[] decode = Base64.decode(myString, Base64.NO_WRAP);
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(decode);
int read;
try {
GZIPInputStream gzipInputStream = new GZIPInputStream(byteArrayInputStream);
BufferedReader br = new BufferedReader(new InputStreamReader(gzipInputStream));
System.out.println("read222 :" + br.readLine());
DataInputStream dataInputStream = new DataInputStream(gzipInputStream);
//System.out.println("read222 :" + dataInputStream.retoString());
for (int i = 0; i < decode.length; i++) {
read = dataInputStream.readInt();
int rRead = Integer.reverseBytes(read);
System.out.println("read :" + dataInputStream.read());
}
} catch (IOException e) {
e.printStackTrace();
}
}

run your code in a thread or asynctask or service whereever you want
Thread thread=new Thread(new Runnable()
{
#Override
public void run()
{
try
{
String body = "Naval is working on zip and unzip processed return json";
URL url = new URL("http://yourServerUrl/yourgzip.php");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
conn.setRequestProperty("Content-encoding", "gzip");
conn.setRequestProperty("Content-type", "application/octet-stream");
GZIPOutputStream dos = new GZIPOutputStream(conn.getOutputStream());
dos.write(body.getBytes());
dos.flush();
dos.close();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder builder=new StringBuilder();
String decodedString = "";
while ((decodedString = in.readLine()) != null)
{
builder.append(decodedString);
}
in.close();
Log.e("Data", builder.toString());
}
catch (Exception e)
{
Log.e("Datae", builder.toString());
}
}
});
thread.start();
on server side ask them to use this code
$postdata=gzinflate( substr($HTTP_RAW_POST_DATA,10,-8) );
as $HTTP_RAW_POST_DATA deprecated so use file_get_contents() like to return array
$post = array_map('urldecode',explode('&',file_get_contents("php://input")));
or like this method to decompress a gzip stream that was pushed to my webserver
$x = file_get_contents("compress.zlib://php://input");
and using
$data_as_associate_Array=json_decode($x,true);

Related

BufferedReader UTF-8 BOM

I have a method in Java where I try to get one integer (user id) through a POST json request, this is the method:
public static Integer getUserIdOwnerOfMsg(Message msg) {
Integer idUser = null;
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("textMsg", msg.getTextMsg());
jsonObject.put("hourMsg", msg.getHourMsg());
List list = new LinkedList();
list.addAll(Arrays.asList(jsonObject));
String jsonString = list.toString();
String urlStr = SERVER_PATH + "getUserIdOwnerOfMsgJSON.php";
URL url = new URL(urlStr);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "your user agent");
con.setRequestProperty("Accept-Language", "sp,SP;q=0.5");
//con.setRequestProperty("Content-Type", "text/html; charset=UTF-8");
String urlParameters = "json=" + jsonString;
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
InputStream instream;
int status = con.getResponseCode();
if (status != HttpURLConnection.HTTP_OK)
instream = con.getErrorStream();
else
instream = con.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(instream, "UTF-8")); // ISO-8859-1
in.mark(1);
if(in.read() != 0xFEFF)
in.reset();
String inputLine;
StringBuilder response = new StringBuilder();
while((inputLine = in.readLine()) != null)
response.append(inputLine);
in.close();
JSONObject object = new JSONObject(response.toString());
Boolean correct = object.getBoolean("correct");
if (correct) {
idUser = object.getInt("id");
}
} catch (Exception e) {
e.printStackTrace();
}
return idUser;
}
The problem is that the response contains a UTF-8 BOM character, on postman the result it's ok and I can see the id: ({"id":"7","correct":true})
But debugging on android studio I got the value "" or null for idUser, I don't know why, I've tried so many ways to resolve this problem without succeed.
Also on the php server side I've executed echo mb_detect_encoding($idUsuario); and I got ASCII encoding in case that could help to find the solution.
Any help will be apreciated, thank you!
So finally I got the solution, I post it here in case someone have the same issue as me, the problem was with the parameters of the JSON, because they included UTF-8 characters like €, so instead of reading the parameters like this:
wr.writeBytes (urlParameters);
I have to do this:
byte[] buf = urlParameters.getBytes("UTF-8");
wr.write(buf, 0, buf.length);
I post also the complete function in case someone needs it:
public static Integer getUserIdOwnerOfMsg(Message msg) {
Integer idUser = null;
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("textMsg", msg.getTextMsg());
jsonObject.put("hourMsg", msg.getHourMsg());
List list = new LinkedList();
list.addAll(Arrays.asList(jsonObject));
String jsonString = list.toString();
String urlStr = SERVER_PATH + "getUserIdOwnerOfMsgJSON.php";
URL url = new URL(urlStr);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "your user agent");
con.setRequestProperty("Accept-Language", "sp,SP;q=0.5");
String urlParameters = "json=" + jsonString;
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream (con.getOutputStream());
byte[] buf = urlParameters.getBytes("UTF-8");
wr.write(buf, 0, buf.length);
wr.flush();
wr.close();
InputStream instream;
int status = con.getResponseCode();
if (status != HttpURLConnection.HTTP_OK)
instream = con.getErrorStream();
else
instream = con.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(instream, Charset.forName("UTF-8")),8192);
String inputLine;
StringBuilder response = new StringBuilder();
while((inputLine = in.readLine()) != null)
response.append(inputLine);
JSONObject object = new JSONObject(response.toString());
Boolean correct = object.getBoolean("correct");
if (correct) {
try {
String idUserText = object.getString("id");
idUser = Integer.valueOf(idUserText);
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}
return idUser;
}
That's all, happy coding!

Compress the image with base64 and send post from android to php

ByteArrayOutputStream bytearray = new ByteArrayOutputStream();
mBitmapProfile.compress(Bitmap.CompressFormat.JPEG, 100, bytearray);
String base64 = Base64.encodeToString(bytearray.toByteArray(), Base64.DEFAULT);
String data = URLEncoder.encode("SOURCE", "UTF-8") + "=" base64;
String result = getHttpData("http://example/p.php", data);
private String getHttpData(String httpUrl, String param) {
String urlString = httpUrl;
String data = param;
try {
URL url = new URL(urlString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
// urlConnection.setConnectTimeout(CONNECTION_TIMEOUT);
// urlConnection.setReadTimeout(DATARETRIEVAL_TIMEOUT);
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
wr.write(data);
wr.flush();
int responseCode = urlConnection.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader br=new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String response = "";
String line = "";
while ((line = br.readLine()) != null) {
response+=line;
}
return response;
}
} catch(MalformedURLException e){
e.printStackTrace();
return null;
} catch(IOException e) {
e.printStackTrace();
return null;
}
return "";
}
After base64 encoding the image
Using POST, making requests from Android to PHP will cause problems.
ex)
android send data : /9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBA+BAQEBAQE==
php receive data : /9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBABAQEBAQE
Some special characters are lost.
Why is that so?
The problem is that base64 encoded data can contain '+' characters. In x-www-form-urlencoded data the receiver knows that '+' is an encoding of a space character. Thus since you aren't URL encoding your base64 value, any instances of '+' will cause the data to be corrupted when received.

Base64 encoding product different result

I am working on android project which can upload image from user's phone galery. The method i use to upload the image is to encode the image to base64 in android and send it to PHP files on server, then the PHP file decodes it then put it on server.
But the problem is the result of PHP decoding is different with the original image. Although the image is still working, but i am afraid sometimes it's gonna be a bug :D..
How to solve it?
Class UploadImageCatalog
#Override
protected String doInBackground(String... params) {
String urlAPI = params[0];
String id = params[1];
String imageByte = params[2];
try {
URL url = new URL(urlAPI);
HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
urlCon.setReadTimeout(15000);
urlCon.setConnectTimeout(15000);
urlCon.setDoOutput(true);
urlCon.setRequestMethod("POST");
OutputStream os = urlCon.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
BufferedWriter bw = new BufferedWriter(osw);
String postData = URLEncoder.encode("id", "UTF-8")+"="+URLEncoder.encode(id, "UTF-8")+"&"+
URLEncoder.encode("imageByte", "UTF-8")+"="+URLEncoder.encode(imageByte, "UTF-8");
bw.write(postData);
bw.flush();
bw.close();
osw.close();
os.close();
urlCon.connect();
int responseCode = urlCon.getResponseCode();
if (responseCode == HTTP_OK) {
InputStream is = urlCon.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String responseString = br.readLine();
br.close();
isr.close();
is.close();
return responseString;
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
Method getStringImage()
private String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
return Base64.encodeToString(imageBytes, Base64.DEFAULT);
}
Mehthod to upload image
btSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (updateImage) {
new UploadImageCatalog(ViewProductActivity.this)
.execute(SERVER_URL+"/project/katalogmukenalukis/uploadimage.php",
String.valueOf(idToView), getStringImage(imageLoadedBitmap));
} else {
updateData();
}
}
});
uploadimage.php
<?php
$id = $_POST['id'];
$imageByte = $_POST['imageByte'];
$target = __DIR__."/asset/".$id;
if (file_exists($target)) {unlink($target);}
if (file_put_contents($target, base64_decode($imageByte))) {
echo json_encode(array("success" => true));
} else {
echo json_encode(array("success" => false, "message" => ""));
}
?>

How to display an image from mysql php into android?

I am currently trying to display an image from mysql database into my android program using an image view. However, it does not work the way I wanted to yet. The following is the php code i currently have:
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
require 'connect_aircraftoperator.php';
$image = $db->query("SELECT companyImage FROM company where companyID = 2");
$getImage = $image->fetch_assoc();
$upload = $getImage['companyImage'];
header("Content-type: image/png");
echo $upload;
?>
The code displays the image just fine in the browser. The following is my current android code
void getImage() {
//String imageResult = "";
//JSONObject jArray = null;
//String Qrimage;
//Bitmap bmp;
try {
//setting up the default http client
HttpClient httpClient = new DefaultHttpClient();
//specify the url and the name of the php file that we are going to use
//as a parameter to the HttpPost method
HttpPost httpPost = new HttpPost("http://10.0.2.2//aircraftoperatorapp/leimage.php");
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch (Exception e) {
System.out.println("Exception 1 Caught ");
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
//create a string builder object to hold data
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line+"\n");
}
//use the toString() method to get the data in the result
imageResult = sb.toString();
is.close();
//checks the data by printing the result in the logcat
System.out.println("---Here's my data---");
System.out.println(imageResult);
}
catch (Exception e){
System.out.println("Exception 2 Caught ");
}
try {
//creates json array
JSONArray jArray = new JSONArray(imageResult);
for (int i = 0; i < jArray.length(); i++)
{
//create a json object to extract the data
JSONObject json_data = jArray.getJSONObject(i);
imageTemp = json_data.getString("companyImage"); //gets the value from the php
}
lblTesting3.setText(imageTemp);
byte[] data = Base64.decode(imageTemp, 0);
Bitmap b = BitmapFactory.decodeByteArray(data,0,data.length,null);
imgCompany.setImageBitmap(b);
}
catch (Exception e){
//System.out.println("Exception 3 Caught ");
Log.e("lag_tag", "Error Parsing Data " + e.toString());
}
}
All I have returning is some text that probably has to do with the image I'm returning. The following text is like this in the beginning:
ÿØÿáhExifMM*vž¤¬(1´2Ò‡iè ü€' ü€..... and so on.
Is there a way I can convert this into an image that is displayable into my android program with the code I have or do I have to do something more different? I would appreciate anyone would help me! It would mean a lot! Thanks in advance!
I think the issue you're facing with is a simple decoding mistake.
HttpEntity entity = response.getEntity();
is = entity.getContent();
The InputStream you're getting from the HttpEntity contains binary image data. So you can simply copy that data into an bytearray:
...
Bitmap bitmap;
byte[] image = null;
...
ByteArrayOutputStream out = new ByteArrayOutputStream();
copy(in, out, true);
image = out.toByteArray();
in.close();
bitmap = BitmapFactory.decodeByteArray(image, 0, image.length);
...
public static void copy(InputStream in, OutputStream out, boolean close)
throws IOException
{
if (in != null && out != null)
{
byte[] buffer = new byte[4096];
int count;
while ((count = in.read(buffer)) > 0)
out.write(buffer, 0, count);
if (close)
{
in.close();
out.close();
}
}
}

Android: How to get image from remote server

I am developing an Android app that should get an image from remote server. Am using WAMP as my server and PHP as programming language. I know how to get text data using JSON.
Am not using blob to store image.
Images have stored in a folder on server. Url of image is stored in db table.
I tried the following snippet, I got this from net but it is not giving any error and also it is not displaying image
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://10.0.2.2/sareesProject/returnSareeTypeImageUrls.php");
response = httpClient.execute(httpPost);
entity = response.getEntity();
if(response.getStatusLine().getStatusCode() == 200)
{
Log.d("Http Response:", response.toString());
if(entity != null)
{
InputStream instream = entity.getContent();
JSONObject jsonObj = new JSONObject(convertStreamToString(instream));
String base64Image = jsonObj.getString("pprs");
Toast.makeText(getBaseContext(), base64Image, Toast.LENGTH_LONG).show();
byte[] rawImage = Base64.decode(base64Image, Base64.DEFAULT);
bmp = BitmapFactory.decodeByteArray(rawImage, 0, rawImage.length);
}
}
ImageView imageview = (ImageView) findViewById(R.id.flag);
imageview.setImageBitmap(bmp);
The following is my php code
<?php
error_reporting( E_ALL ^ E_NOTICE ^ E_WARNING);
$con = mysql_connect("localhost","root","") or die("con error");
mysql_select_db("sareesdb") or die("db select eror");
$query = mysql_query("select * from noofpiecesinatype");
if($row = mysql_fetch_assoc($query))
{
$response = $row['imageUrl'];
}
$response = base64_encode($response);
echo '{"pprs":'.json_encode($response).'}';
mysqli_close($con);
?>
I checked my php code with html(with out encoding $response value) am getting image there, but not in Android.
I am not good with Php, but if you return the file url via a JSON reponse you can use the following code for downloading the file.
int count;
try {
URL url = new URL("http://url of your file");
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
// Output stream to write file
OutputStream output = new FileOutputStream("/sdcard/downloadedfile.jpg");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress(""+(int)((total*100)/lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
## Edit ##
After the Image is downloaded you can create a Bitmap from the Image Path/InputStream and assign it to the Image View like this
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
Bitmap bmp = BitmapFactory.decodeStream(bufferedInputStream);
Original source
try {
httpClient = new DefaultHttpClient();
httpPost = new HttpPost("http://10.0.2.2/sareesProject/returnSareeTypeImageUrls.php");
response = httpClient.execute(httpPost);
entity = response.getEntity();
if(response.getStatusLine().getStatusCode() == 200)
{
Log.d("Http Response:", response.toString());
if(entity != null)
{
instream = entity.getContent();
JSONObject jsonObj = new JSONObject(convertStreamToString(instream));
bitmapPath = jsonObj.getString("pprs");
}
}
try {
Toast.makeText(getBaseContext(), "http://10.0.2.2/sareesProject/"+bitmapPath, Toast.LENGTH_SHORT).show();
URL url = new URL("http://10.0.2.2/sareesProject/"+bitmapPath);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
bmp = myBitmap;
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
}
if(bmp == null)
Toast.makeText(getBaseContext(), "null", Toast.LENGTH_SHORT).show();
ImageView imageview = (ImageView) findViewById(R.id.flag);
imageview.setImageBitmap(bmp);
} catch (Exception e) {
// TODO: handle exception
Toast.makeText(getBaseContext(),e.getMessage(), Toast.LENGTH_LONG).show();
}
private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
//new HomePage().show("in con");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
//show(line);
//new HomePage().show("in while");
//new HomePage().show("l="+line);
sb.append(line+"\n");
}
} catch (IOException e) {
e.printStackTrace();
//Toast.makeText(, text, duration)
} finally {
try {
if(reader != null)
{
try{reader.close();}
catch(Exception e){e.printStackTrace();}
}
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}//end of convertStreamToString
The following is my php code
<?php
error_reporting( E_ALL ^ E_NOTICE ^ E_WARNING);
$con = mysql_connect("localhost","root","") or die("con error");
mysql_select_db("sareesdb") or die("db select eror");
$query = mysql_query("select * from noofpiecesinatype");
$response = array();
while($row = mysql_fetch_assoc($query))
{
$response[] = $row['imageUrl'];
}
echo json_encode($response);
mysqli_close($con);
?>
//--------------------
Fnally i got it.............
First of all my server file returns the following
{"pprs":"upload/22.png"}
from this i extracted upload/22.png using JSON
Now bitmapPath contains upload/22.png
Thank you very much to insomniac giving suggestions.............
If it is helpful to any one vote for me..............

Categories