Base64 encoding product different result - php

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" => ""));
}
?>

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!

How to send audio file to the server in android?

I am writing code to send audio file from android application to the server. The connection is working well, but I don't know how to make the file to save on the server.
My question is : How can I send audio file to server?
Can you please explain me what exactly should I do step by step? I think I am wrong somewhere on the part of encoding file..
public class UploadRecordingAsyncTask extends AsyncTask<String,Void, Void>{
String fileName;
String filePath;
String username;
public UploadRecordingAsyncTask(String filePath, String fileName, String username){
this.filePath = filePath;
this.fileName = fileName;
this.username = username;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(String... params) {
try{
URL url = new URL(SERVER_ADDRESS + "UploadRecording.php");
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
//past information
httpURLConnection.setDoOutput(true);
//get outputstreamwrite from http connection
OutputStream outputStream = httpURLConnection.getOutputStream();
//write down information
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, ENCODING_FORMAT));
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//Encoding file part from here
FileInputStream fileInputStream = new FileInputStream(new File(filePath));
InputStream inputStreamFile = new BufferedInputStream(fileInputStream);
int numOfBytes = inputStreamFile.available();
byte[] audioBytesFile = new byte[numOfBytes];
int i = inputStreamFile.read(audioBytesFile,0,numOfBytes);
String audioString = Base64.encodeToString(audioBytesFile, 0);
inputStreamFile.close();
//encode data before sending
String data = URLEncoder.encode("filename", ENCODING_FORMAT) + "=" + URLEncoder.encode(fileName, ENCODING_FORMAT) + "&" +
URLEncoder.encode("owner", ENCODING_FORMAT) + "=" + URLEncoder.encode(username, ENCODING_FORMAT) + "&" +
URLEncoder.encode("encodedfile", ENCODING_FORMAT) + "=" + URLEncoder.encode(audioString, ENCODING_FORMAT) + "&";
//write data into buffer writer
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
//input stream to get response from the server
InputStream inputStream = httpURLConnection.getInputStream();
inputStream.close();
httpURLConnection.disconnect();
}catch(MalformedURLException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
progressDialog.dismiss();
super.onPostExecute(aVoid);
}
}
And on the server I have php file :
<?php
require "init.php";
if(isset($_POST["encodedfile"])){
$filename = $_POST["filename"];
$owner = $_POST["owner"];
$decoded_string = base64_decode($_POST["encodedfile"]);
$path = "recordings/".$filename;
//new file of audio
$file = fopen($path, 'wb');
to_write_file = fwrite($file, $decoded_string);
fclose($file);
$query = "INSERT INTO Recording (filename, owner, encodedfile) VALUES (?,?,?)";
if($stmt = mysqli_prepare($connectDB, $query)){
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, 'sss', $filename, $owner, $decoded_string);
/* execute line*/
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
}
mysqli_close($connectDB);
}
?>

POST json data using HttpURlConnection

I am trying to send json data to server using HTTPURLConnection. But every time response id null from server. i tried by POSter also but it is working there.
try {
jsondata ="{\"A\":\"1234\",\"country_code\":\"91\",\"name\":\"sajal\",\"phone_number\":\"88999\"}";
URL url = new URL(uri);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
httpConn.setConnectTimeout(3000);
httpConn.setDoInput(true);
httpConn.setDoOutput(true);
httpConn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
httpConn.setRequestMethod("POST");
StringBuffer requestParams = new StringBuffer();
if (jsondata != null && jsondata.length() > 0) {
Uri.Builder builder = new Uri.Builder().appendQueryParameter("data", jsondata);
String query = builder.build().getEncodedQuery();
OutputStream os = httpConn.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
bufferedWriter.write(query);
bufferedWriter.flush();
bufferedWriter.close();
os.close();
}
InputStream inputStream = null;
if (httpConn != null) {
inputStream = httpConn.getInputStream();
} else {
throw new IOException("Connection is not established.");
}
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
response = reader.readLine();
reader.close();
if (httpConn != null)
httpConn.disconnect();
} catch (UnknownHostException one) {
return response;
} catch (SocketException two) {
return response;
} catch (Exception three) {
return response;
}
return response;
}
Keeping my json string in "data" key
PHP:-
if (isset($_POST['data'])) {
$data = json_decode($_POST["data"], true);
// php code.....
} else {
// control comes here..
// php code.....
}
Here $_POST['data'] is not working. Please check whats wrong in PHP or Andooid code.

Data getting inserted multiple times - android, php

In my project, I'm sending data from an android device and it is inserted into a database using a php script. But the same data is inserted twice. (please see here)
What is wrong with my code?
Android:
try {
String data=URLEncoder.encode("name", "UTF-8")+"="+URLEncoder.encode(Name, "UTF-8");
data+="&"+URLEncoder.encode("family", "UTF-8")+"="+URLEncoder.encode(Family, "UTF-8");
data+="&"+URLEncoder.encode("city", "UTF-8")+"="+URLEncoder.encode(City, "UTF-8");
data+="&"+URLEncoder.encode("ostan", "UTF-8")+"="+URLEncoder.encode(Ostan, "UTF-8");
data+="&"+URLEncoder.encode("tel", "UTF-8")+"="+URLEncoder.encode(Tel, "UTF-8");
data+="&"+URLEncoder.encode("sef", "UTF-8")+"="+URLEncoder.encode(sef1, "UTF-8");
data+="&"+URLEncoder.encode("bod", "UTF-8")+"="+URLEncoder.encode(bodjeh1, "UTF-8");
data+="&"+URLEncoder.encode("tab", "UTF-8")+"="+URLEncoder.encode(tabgh, "UTF-8");
data+="&"+URLEncoder.encode("img", "UTF-8")+"="+URLEncoder.encode(imgs, "UTF-8");
data+="&"+URLEncoder.encode("imgf", "UTF-8")+"="+URLEncoder.encode(fimage, "UTF-8");
URL link=new URL(MainActivity.url+"/app/order.php");
URLConnection con=link.openConnection();
con.setDoOutput(true);
OutputStreamWriter wrw=new OutputStreamWriter(con.getOutputStream());
wrw.write(data);
wrw.flush();
BufferedReader br=new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder sb=new StringBuilder();
String l="";
while((l=br.readLine())!=null){
sb.append(l);
}
r=sb.toString();
br.close();
Code for insertion - php
$name=$_POST['name'];
$family_name=$_POST['family'];
$city=$_POST['city'];
$ostan=$_POST['ostan'];
$tel=$_POST['tel'];
$comment=$_POST['sef'];
$bod=$_POST['bod'];
$tab=$_POST['tab'];
$img=$_POST['img'];
$imgf=$_POST['imgf'];
$sql="INSERT INTO `customer_table`(`id`, `name`, `family_name`, `city`, `ostan`, `tel`, `comment`,`bodjeh`,`tabagheh`,`imag_f`,`image`)
VALUES ('','$name','$family_name','$city','$ostan','$tel','$comment','$bod','$tab','$imgf','$img')";
Please use below method to send data to server
First convert your request json into simple map like
Map<String, String> map = new HashMap<>();
map.put("name", Name);.....so on
Then use below method to call the Webservice.
private JSONObject sendRequest(String urlString, Map<String, String> map, String fileKey, File file) {
StringBuilder strData= null;
JSONObject resObj = null;
try {
Log.i("Send request", urlString+"="+map);
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(50000);
conn.setConnectTimeout(50000);
conn.setRequestMethod("POST");
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
if(map == null)
{
map = new HashMap<>();
}
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
for (HashMap.Entry<String, String> entry : map.entrySet()) {
String k = entry.getKey();
String v = entry.getValue();
reqEntity.addPart(k, new StringBody(v));
}
if(file != null && !TextUtils.isEmpty(fileKey))
{
FileBody filebody = new FileBody(file, "image/*");
reqEntity.addPart(fileKey, filebody);
}
conn.setRequestProperty("Connection", "Keep-Alive");
conn.addRequestProperty("Content-length", reqEntity.getContentLength() + "");
conn.addRequestProperty(reqEntity.getContentType().getName(), reqEntity.getContentType().getValue());
OutputStream os = conn.getOutputStream();
reqEntity.writeTo(os);
os.close();
conn.connect();
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String sResponse;
strData = new StringBuilder();
while ((sResponse = reader.readLine()) != null) {
strData = strData.append(sResponse);
}
}
if(strData != null)
resObj = new JSONObject(strData.toString());
} catch (Exception e) {
e.printStackTrace();
}
return resObj;
}
As your php code you need to do :
$result = mysql_query($sql);
if(count($result) > 0)
{
echo "1";
}else
{
echo "0";
}

gzip compression in android app as client and php server

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

Categories