My app sends a POST request that way:
URL url = new URL(SERVER_URL);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod(method);
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.connect();
// Write
OutputStream output = urlConnection.getOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(output, "UTF-8");
writer.write(jsonString);
writer.close();
output.close();
urlConnection.disconnect();
But the API can't decode it because it is a string. So:
$input = json_decode(file_get_contents('php://input'), true);
just returns an empty array.
How do I write just the JSON in the body of the request?
Maybe you need to parse your jsonString. So your code should be:
writer.write(JSON.parse(jsonString));
Related
I am sending user email from Android app to PHP using HttpUrlConnection but PHP is not receiving Any data from App. This type of questions have already been asked but their solution do not worked for me. My Android Coding is
URL server_url = new URL("http://www.myURL.com/Jobs/login.php");
HttpURLConnection urlc = (HttpURLConnection) server_url.openConnection();
urlc.setDoOutput(true);
urlc.setDoInput(true);
urlc.setRequestMethod("POST");
urlc.setRequestProperty("Content-Language", "en-US");
urlc.setRequestProperty("Accept-Encoding", "identity");
urlc.connect();
HashMap<String, String> param = new HashMap<>();
param.put("email", mEmail);
DataOutputStream os = new DataOutputStream(urlc.getOutputStream());
os.writeBytes(URLEncoder.encode(mEmail, "UTF-8"));
os.flush();
os.close();
and My php code is:
<?php
$user_email=$_POST['email'];
echo "Email is $user_email";
?>
but when running this php on browser, it is echoing "Email is" as it is not receiving any data from android. Please Help
My php code contains only these two lines. Am I missing something in php coding?
You're not sending the paramater at all. You need to structure the request much better aswell since it's clear you're getting confused.
URL server_url = new URL("http://www.myURL.com/Jobs/login.php");
HttpURLConnection urlc = (HttpURLConnection) server_url.openConnection();
//header stuff
urlc.setRequestMethod("POST");
urlc.setRequestProperty("Content-Language", "en-US");
urlc.setRequestProperty("Accept-Encoding", "identity");
//params
String urlParameters = "email="+mEmail;
//send post
urlc.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(urlc.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
//read result
BufferedReader in = new BufferedReader(
new InputStreamReader(urlc.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString()
);
After so many solutions and discussion finally i got the solution..can not say solution but an alternative approach and it is " volley" library...i used it..and finally php receives the data....
I'm working on an application that allows data transfer from Android to PHP server and I don't know why it doesn't support JSON?
Here is my code:
<?php
JSON.parse();
$decode = json_decode($_REQUEST['request']);
$json = $decode->name;
header('Content-type:application/json');
echo json_encode($json);
?>
check your JSON at http://jsonlint.com
If the JSON is valid than your php code may not be correct.
Show some code for specifics.
You can send Json data as string from android using following code :
BufferedReader reader = null;
// Send data
try {
/* forming th java.net.URL object */
URL url = new URL(this.url);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setRequestMethod("POST");
urlConnection.connect();
/* pass post data */
byte[] outputBytes = jsonData.toString().getBytes("UTF-8");
OutputStream os = urlConnection.getOutputStream();
os.write(outputBytes);
os.close();
/* Get Response and execute WebService request*/
int statusCode = urlConnection.getResponseCode();
/* 200 represents HTTP OK */
if (statusCode == HttpsURLConnection.HTTP_OK) {
inputStream = new BufferedInputStream(urlConnection.getInputStream());
ResponseData= convertStreamToString(inputStream);
} else {
ResponseData = null;
}
and in php,you can get data by adding following code :
$post_body = file_get_contents('php://input');
$post_body = iconv('UTF-8', 'UTF-8//IGNORE', utf8_encode($post_body));
$reqData[] = json_decode($post_body);
$postData = $reqData[0];
echo $postData->name;
I want to send data from android to php.Am using android api 23 and from android's developers site a got to know that namepairvalue is deprecated from api 22 and above. I referred to one of the post here in stackoverflow and got the below code. but still it doesn't work.
My problem is that am sending a value(ID) to php code and based on that value fetching the records from database. Now if i fetch data without using this value it works fine, but i am unable to send the id value to php code.
i am unable to find whats wrong in this code or may be my fault is editing the code. It would be great if someone helps me to understand it clearly .
Thank you in advance.
Here is the code snippet that i have tried.
Android Code:
String sid = staffid.toString(); // this sid is passed as intent from another activity and passing it to below link.
Log.d("SID :", "" + sid);
try {
URL url = null;
url = new URL("http://usplhubli.96.lt/hrm/hrm_app/individual_view_staff.php");
Log.d("url to display :", "" + url.toString());
HttpURLConnection conn = null;
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(CONNECTION_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
DataOutputStream os = new DataOutputStream(conn.getOutputStream());
// Log.d("os to display :", "" + os.toString());
Uri.Builder builder = new Uri.Builder().appendQueryParameter("sid", sid);
Log.d("builder to display :", "" + builder.toString());
String query = builder.build().getEncodedQuery();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
Log.d("writer display :", "" + writer.toString());
writer.write(query);
writer.flush();
writer.close();
os.close();
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (ProtocolException e2) {
e2.printStackTrace();
} catch (IOException e3) {
e3.printStackTrace();
}
return null;
}
I have this code in doInBackground(String... params) of AsyncTask
based on this sid value i have to get the data from database and display it in android activity.
Here is the PHP code that i have tried
PHP Code:
$response=array();
$sid=$_POST["sid"]; // this is the POST data that am send from android
//$sid="4"; // this is the static value that i have tried and its working
print_r($sid);
include 'dbconfig.php';
$imagePath='http://www.usplhubli.96.lt/hrm';
$query=mysqli_query($conn,"select * from hrm_staff where sid='$sid'");
if(mysqli_num_rows($query) >0) {
$response["hrm_staff"] = array();
while ($row = mysqli_fetch_array($query)) {
$recp = array();
$recp["sid"]=$row["sid"];
$fullName=$row['fname']."".$row['mname']."".$row['lname'];
$recp["name"]= $fullName;
$recp["address"]=$row['address'];
$recp['city']=$row['city'];
$recp["design"]=$row['did'];
$recp["contact"]=$row['mobile'];
$recp["email"]=$row['email'];
$recp['qualification']=$row['quali'];
$recp["dateofjoining"]=$row['doj'];
$ppic1=$row['ppic'];
$ppic1;
$ppic21=$imagePath."/".trim($ppic1);
$recp["ppic"]= $ppic21;
array_push($response["hrm_staff"], $recp);
}
$response["success"] = 1;
$response["message"]="display records";
echo json_encode($response);
}
else
{
$response["success"] = 0;
$response["message"] = "No products found";
echo json_encode($response);
}
Please suggest. Thank you.
use these lines of code for using HttpURLConnection
For sending the request parameter are as:-
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("phone", number)
.appendQueryParameter("password", password)
.appendQueryParameter("device_login",value);
And for the getting the request parameter in the post method of connectionUrl are as follow:-
URL url = new URL(myurl);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(30000);
urlConnection.setConnectTimeout(30000); ;
String query = builder.build().getEncodedQuery();
System.out.println("REQUEST PARAMETERS ARE===" + query);
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.connect();
//Send request
DataOutputStream wr = new DataOutputStream (
urlConnection.getOutputStream ());
wr.writeBytes (query);
wr.flush ();
wr.close ();
//Get Response
InputStream isNew = urlConnection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(isNew));
String line;
response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
}
rd.close();
System.out.println("Final response===="+response);
There might be more than one issue but a big one is you never send the request, all you are doing is creating the request and setting up the parameters
you need to do a
conn.connect();
or
conn.getInputStream();
or any number of things you can do to send the request and get the information you require
AFTER you write your params
I'm wondering what the format of a json is suppose to be since it seems php and android has two different types.
When encode the php, it looks like this:
{"id":8435,"name":"Sears"}
{"id":8436,"name":"Sears Appliance Services"}
But when I try to decode in android. It comes out as one big string in android (because it's just viewing the source code of the php page).
This is the code:
Php:
echo json_encode($results[$i]);
Android:
url = new URL("site");
String param = "arg1=" + URLEncoder.encode("value1", "UTF-8");
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setFixedLengthStreamingMode(param.getBytes().length);
conn.setRequestProperty("Content-Type","application/x-www-form- urlencoded");
PrintWriter out = new PrintWriter(conn.getOutputStream());
out.print(param);
out.close();
InputStream is = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String s;
while ((s = reader.readLine()) != null) {
result += s;
}
JSONObject jObject = new JSONObject(result);
How can I get the data this method is forwarding to a PHP webpage ?
URL url;
HttpURLConnection connect = null;
BufferedReader rd;
StringBuilder sb;
OutputStreamWriter wr;
// Change this url to the url of your receiveJsonSms.php.
String urlString = "http://www.paintedostrich.com/receiveJsonSms.php";
try {
System.setProperty("http.keepAlive", "false");
url = new URL(urlString);
connect = (HttpURLConnection) url.openConnection();
connect.setRequestMethod("POST");
connect.setDoOutput(true);
connect.setDoInput(true);
connect.setReadTimeout(10000);
connect.connect();
// write to the stream
String data = URLEncoder.encode("texts", "UTF-8") + "="
+ URLEncoder.encode(jsonTexts.toString(), "UTF-8");
wr = new OutputStreamWriter(connect.getOutputStream());
wr.write(data);
wr.flush();
// read the result from the server
rd = new BufferedReader(new InputStreamReader(connect.getInputStream()));
sb = new StringBuilder();
String line = null;
while ((line = rd.readLine()) != null) {
sb.append(line);
}`
To decode json in PHP use json_decode().
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
var_dump(json_decode($json, true));
?>
I think the answer is
sb.ToString();
thats the data you get from the server if you want to read the JSON use this
http://www.codeproject.com/Tips/397574/Use-Csharp-to-get-JSON-data-from-the-web-and-map-i