JSON_ERROR_SYNTAX sending Json request via Android App - php

I m trying to send a Json Post request using my Android Application.
But something weird happens.
Here is my Android Code:
try {
URL url = new URL(BASE_URL + params[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type","application/json");
connection.connect();
//JSonObject
JSONObject json = new JSONObject();
for(int i = 0 ; i < jsonValues.size(); i +=2){
json.put(jsonValues.get(i), jsonValues.get(i + 1));
}
jsonValues.clear();
DataOutputStream output = new DataOutputStream(connection.getOutputStream());
//String encoded= URLEncoder.encode(json.toString(),"UTF-8");
output.writeBytes(URLEncoder.encode(json.toString(),"UTF-8"));
output.flush();
output.close();
int HttpResult = connection.getResponseCode();
if(HttpResult ==HttpURLConnection.HTTP_OK){
BufferedReader br = new BufferedReader(new InputStreamReader(
connection.getInputStream(),"UTF-8"));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
String lineDecoded = URLDecoder.decode(line, "UTF-8");
sb.append(lineDecoded + "\n");
}
br.close();
System.out.println(""+sb.toString());
if(sb != null){
return sb.toString();
}else{
return null;
}
}else{
Log.d("ERRORRRRR",connection.getResponseMessage());
return connection.getResponseMessage();
}
} catch (MalformedURLException e) {
e.printStackTrace();
return e.toString();
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} catch (JSONException e) {
e.printStackTrace();
return e.toString();
}
My php code is this:
$content = file_get_contents("php://input");
if(strcasecmp($_SERVER['REQUEST_METHOD'], 'POST') != 0)
{
throw new Exception('Request method must be POST!');
}
//Make sure that the content type of the POST request has been set to
application/json
$contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
if(strcasecmp($contentType, 'application/json') != 0){
throw new Exception('Content type must be: application/json');
}
//Receive the RAW post data.
$content = trim(file_get_contents("php://input"));
//Attempt to decode the incoming RAW post data from JSON.
$decoded = json_decode($content, true);
echo($decoded);
exit;
The $decoded is null when I make a request using my Android application and using json_last_error() function I get JSON_ERROR_SYNTAX.
This is the raw content of the post request:
{"name":"test","identifier":"12345677"}
But I can't understand what is the problem. In fact when I try to use Advance Rest Client to simulate the same request it works perfectly as shown in the picture below.

I finally solved my Problem.. It seems to be the
URLEncoder.encode(json.toString(),"UTF-8");
In fact removing it and sending just output.writeBytes(json.toString());
Everything works perfectly

Related

How to send data from android to mysql?

I want to send data from android to php file which is adding data to mysql database using POST method, i have no idea how i coult bite this.. any help?
I already connected with http by method post.. and no clue what now...
public URL makeUrl(String stringUrl) {
URL url = null;
try {
url = new URL(stringUrl);
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Problem building the URL ", e);
}
return url;
}
public static void HttpConnect(URL url) {
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setConnectTimeout(15000 /* milliseconds */);
urlConnection.setRequestMethod("POST");
urlConnection.connect();
// If the request was successful (response code 200),
// then read the input stream and parse the response.
if (urlConnection.getResponseCode() == 200) {
//to do
} else {
Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode());
}
} catch (IOException e) {
Log.e(LOG_TAG, "Problem retrieving the JSON results.", e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
}
PHP FILE with adding by POST method.
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
require 'connect.php';
create();
}
function create(){
global $connect;
$name = $_POST["nazwa"];
$ingredients = $_POST["skladniki"];
$price = $_POST["cena"];
$type = $_POST["typ"];
$photo = $_POST["zdjecie"];
$query = "INSERT INTO dania('nazwa','skladniki','cena','typ','zdjecie') VALUES ('$name','$ingredients','$price','$type','$photo');";
mysqli_query($connect, $query) or die (mysqli_error($connect));
mysqli_close($connect);
}
?>
Use Uri.Builder to attach POST payloads and write it on OutputStream,
In Below code, replace YOUR_VALUE1,YOUR_VALUE2,YOUR_VALUE3,YOUR_VALUE4,YOUR_VALUE5 to suitable values which you like to POST it to server.
Also i would recommend this block of code wrapped inside AsyncTask.
Eg.
public static void HttpConnect(URL url) {
StringBuilder stringBuilder = new StringBuilder();
try {
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setConnectTimeout(10000);
httpURLConnection.setReadTimeout(15000);
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
Uri.Builder builder = new Uri.Builder();
builder.appendQueryParameter("nazwa",YOUR_VALUE1);
builder.appendQueryParameter("skladniki",YOUR_VALUE2);
builder.appendQueryParameter("cena",YOUR_VALUE3);
builder.appendQueryParameter("typ",YOUR_VALUE4);
builder.appendQueryParameter("zdjecie",YOUR_VALUE5);
String urlQuery = builder.build().getEncodedQuery();
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTf-8"));
bufferedWriter.write(urlQuery);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
httpURLConnection.connect();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
String line = "";
while ((line = bufferedReader.readLine()) != null){
stringBuilder.append(line).append("\n");
}
// your json response output is here
Log.d("RESULT",stringBuilder.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
For the Complete example, i have written about AsyncTask in my blog

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.

Post multiple data from Android to PHP web service

So far I can send one set of data from Android to PHP web service. I'm hoping to send an array, and have a for loop in the web service. Is that possible? Is that a good solution? In this project, I'm trying to sync SQLite with MySQL.
Here's my code
String username, userid;
username = "Kate";
userid = "3";
String data = "";
try {
data = URLEncoder.encode("username", "UTF-8") + "="
+ URLEncoder.encode(username, "UTF-8");
data += "&" + URLEncoder.encode("userid", "UTF-8") + "="
+ URLEncoder.encode(userid, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String text = "";
BufferedReader reader = null;
try {
URL url = new URL(
address);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(
conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
reader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
text = sb.toString();
} catch (Exception ex) {
} finally {
try {
reader.close();
} catch (Exception ex) { }
}
And this
<?php
include '../inc/connect.php';
include '../inc/class/mysql.class.php';
$name = urldecode($_POST['username']);
$user = urldecode($_POST['userid']);
print " ==== POST DATA =====
Name : $name
Email : $email
User : $user
Pass : $pass";
$ins = mysql_query("INSERT INTO users (UserName, FullName) VALUES ('$name','$user')") or die(mysql_error());
if ($ins) {
echo json_encode(array("result"=>"success","result_txt"=>"Branch sucessfully added."));
exit();
}
?>
You could send the input as JSON and then get PHP to decode it.
So you'd encode all your data in the android app and send it as one big encoded string, possibly using URI encoding or Base64, then in the PHP do:
$data = json_decode($_POST['data']);
If you use base64 then you'd do:
$data = json_decode(base64_decode($_POST['data']));
If you just send it as one string
$data = json_decode(urldecode($_POST['data']));

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..............

Sending Data From Android To Server with JSON data

I am trying sending data from Android application to web server. My android application is working successfully.However php code have problems.
<?php
$json = $_SERVER['HTTP_JSON'];
echo "JSON: \n";
var_dump($json);
echo "\n\n";
$data = json_decode($json,true);
echo "Array: \n";
var_dump($data);
echo "\n\n";
$name = $data['name'];
$pos = $data['position'];
echo "Result: \n";
echo "Name : ".$name."\n Position : ".$pos;
?>
Errors:
Notice: Undefined index: HTTP_JSON in C:\wamp\www\jsonTest.php on line 2
( line 2 : $json = $_SERVER['HTTP_JSON']; )
I couldn't find these problems reason. Can you help me ?
( note: I am using wamp server )
Here is the relevant Android source:
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("10.0.2.2:90/jsonTest.php";);
JSONObject json = new JSONObject();
try {
json.put("name", "flower");
json.put("position", "student");
JSONArray postjson=new JSONArray();
postjson.put(json);
httppost.setHeader("json",json.toString());
httppost.getParams().setParameter("jsonpost",postjson);
System.out.print(json);
HttpResponse response = httpclient.execute(httppost);
if(response != null)
{
InputStream is = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
text = sb.toString();
}
tv.setText(text);
}catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
This code works successfully on android side(no error). But php side has problems..
Thanks.
This isn't where your JSON is:
$json = $_SERVER['HTTP_JSON'];
You possibly meant:
$json = $_POST['HTTP_JSON'];
Where HTTP_JSON is the POST variable name you gave to your JSON in your Android app.
The rest of the errors stem from the fact that json_decode is failing because you're not successfully reading the JSON data from the request. You can check the response of json_decode to check if it was successful as follows:
$data = json_decode($json,true);
if( $data === NULL)
{
exit( 'Could not decode JSON');
}
Finally, passing true as the second parameter to json_encode means it will return an associative array, so you'd access elements like so:
$name = $data['name'];
$pos = $data['position'];
Make sure you read the docs for json_encode so you understand what it's doing.
Edit: Your problem is that you're accessing the $_POST parameter by the wrong name. You should be using:
$json = $_POST['jsonpost'];
Since the following line names the parameter "jsonpost":
httppost.getParams().setParameter("jsonpost",postjson);
Since I don't know how the java client sends the request
I would try :
print_r($_SERVER);
print_r($_GET);
print_r($_POST);
To figure out how it does.
try these lines:
httppost.setHeader("Accept", "application/json");
httppost.setHeader("Content-type", "application/json");

Categories