I try to get a JSON from my server that should echo json_encode me a variable and return a JSON that looks like below. However, everytime I try to debug the code, I got null on builder. I tried to use a .json file that stocks only data in JSON format and it worked. So , I don't understand why my code doesn't work. Is there any problem with my code? Thank you in advance.
{
"id":"714184",
"corpid":"52233",
"staffMail":"",
"smartTags":[],
"formatted_createdDate":"07/02/2018",
"thirdcontactid":"11210400",
"customfields":[
{
"id":0,
"status":"ok",
"formattedVal":""
},
{
"id":2,
"status":"ok",
"formattedVal":""
}
]
}
Java code where I used Asynctask method to connect to my server
public class PHPConnecteur extends AsyncTask<String, Integer, String>{
private HashMap<String, String> parameters;
private String phpToCall;
public PHPConnecteur(HashMap<String, String> params, String phpTC){
phpToCall = phpTC;
parameters = params;
}
#Override
protected void onPreExecute(){
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
//System.setProperty("http.keepAlive", "false");
String dataParsed = "";
try {
String u = "https://api.asii.fr/api/".concat(phpToCall);
URL url = new URL(u);
JSONObject postDataParams = new JSONObject();
Iterator<HashMap.Entry<String, String>> entries = parameters.entrySet().iterator();
while (entries.hasNext()) {
HashMap.Entry<String, String> entry = entries.next();
postDataParams.put(entry.getKey(), entry.getValue());
}
Log.e("params",postDataParams.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
if (parameters.size() > 1){ // si ce n'est pas la liste d'incident
conn.setReadTimeout(15000 );
conn.setConnectTimeout(15000 );
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
}else{
conn.setReadTimeout(15000 );
conn.setConnectTimeout(15000 );
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setDoOutput(true);
}
InputStream stream = new BufferedInputStream(conn.getInputStream());//here is where i should get the output from php
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
StringBuffer builder = new StringBuffer();
String inputString;
while ((inputString = bufferedReader.readLine()) != null) {
builder.append(inputString);// gives me null when debug
}
/*JSONObject topLevel = new JSONObject(builder.toString());
JSONObject main = topLevel.getJSONObject("id");
dataParsed = String.valueOf(main.getDouble("temp"));*/
conn.disconnect();
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return dataParsed;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(final String result) {
//delegate.onTaskCompleted(result);
}
}
You should add "Content-Type:" header in your PHP script.
$data = [];
header('Content-Type: application/json');
echo json_encode($data);
I found the solution. Actually, the JSON i get from my PHP is in the correct format but it just doesn't have a line break. So what I did in my PHP is, I added a JSON_PRETTY_PRINT when echoing the JSON. That's all, problem solved.
echo json_encode($data, JSON_PRETTY_PRINT);
PHP code:
<?php
$host='127.0.0.1';
$uname='root';
$pwd='password';
$db="android";
$con = mysql_connect($host,$uname,$pwd) or die("connection failed");
mysql_select_db($db,$con) or die("db selection failed");
# Request id value that is sent from android
$id=$_REQUEST['id'];
$r=mysql_query("select * from sample where id='$id'",$con);
while($row=mysql_fetch_array($r))
{
$flag[name]=$row[name];
}
print(json_encode($flag));
mysql_close($con);
?>
Then android side code:
public void select() {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id", id));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success ");
} catch (Exception e) {
Log.e("Fail 1", e.toString());
Toast.makeText(getApplicationContext(), "Invalid IP Address",
Toast.LENGTH_LONG).show();
}
try {
BufferedReader reader = new BufferedReader
(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
} catch (Exception e) {
Log.e("Fail 2", e.toString());
}
try {
JSONObject json_data = new JSONObject(result);
// add whatever you would like to parse (all values you are
// sending from PHP)
name = (json_data.getString("name"));
Toast.makeText(getBaseContext(), "Name : " + name,
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Log.e("Fail 3", e.toString());
}
}
Source: http://sampleprogramz.com/android/mysqldb.php
Hope this helps! Good luck!
Related
I am trying to receieve a simple string from my PHP script by using a POST request in Android Studio.
If I write for example echo "Hello"; I can receive this message in my app, but it seems like as soon as I send a POST request my webserver doesen't really get the message.
Here is how I do the POST request in my AsyncTask:
class HTTPReqTask extends AsyncTask<String, Void, String>
{
Activity activity;
OnDataSendToActivity dataSendToActivity;
Context context;
public HTTPReqTask(Context context)
{
this.context = context;
dataSendToActivity = (OnDataSendToActivity) ((Activity) context);
}
#Override
public String doInBackground(String... params)
{
HttpURLConnection urlConnection = null;
String param1 = params[0];
String line = "";
String result = "";
try
{
JsonObject postData = new JsonObject();
postData.addProperty("a", "1");
URL url = new URL(param1);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setChunkedStreamingMode(0);
OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out,"UTF-8"));
writer.write(postData.toString());
int code = urlConnection.getResponseCode();
if (code != HttpURLConnection.HTTP_OK) {
throw new IOException("Invalid response from server: " + code);
}
BufferedReader rd = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
while ((line = rd.readLine()) != null)
{
result += line;
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (urlConnection != null)
{
urlConnection.disconnect();
}
}
return result;
}
#Override
protected void onPostExecute(String s)
{
try
{
if(dataSendToActivity != null)
{
Log.i("Data", s);
dataSendToActivity.sendData(s);
}
}
catch(Exception e)
{
// Nichts
}
}
}
As you can see I am using this:
JsonObject postData = new JsonObject();
postData.addProperty("a", "1");
to generate my POST request.
The postData string is: {"a":"1"}
This is my PHP script:
$post = file_get_contents("php://input");
$data = json_decode($post, true);
print_r($data);
UPDATE 1
I added now writer.flush(); (Thanks to Andy)
Now I'm getting this exception after sendung the request:
java.io.IOException: Invalid response from server: 500
So something with my PHP script is wrong.
Any suggestions?
I found now the problem.
The problem was not serversided as I expected it.
I was logging in my code some informations for the POST request and there I found this:
Log.i("LOG", urlConnection.getOutputStream().toString());
gave me this:
buffer(com.android.okhttp.internal.http.HttpConnection$ChunkedSink#843d1c8).outputStream()
So I commented this line out:
urlConnection.setChunkedStreamingMode(0);
and it works fine. I get all my data I need.
I also updated my PHP script to this:
$post = file_get_contents("php://input");
if (!empty($post))
{
$data = json_decode($post, true);
$a = $data['a'];
}
Thanks for all the help!
i want to send data from android application to tomcat java server.
Data is just one is client_id which is 1 and second is staff_id which is 2.
after authenticate the client id and staff id from tomcat show me a toast of success....please help...
Code is here
public class MyAsyncTasks extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// display a progress dialog for good user experiance
}
#Override
protected String doInBackground(String... params) {
// implement API in background and store the response in current variable
String current = "";
try {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL("http://192.168.1.13:8080/digitaldisplay/s/m/data");
urlConnection = (HttpURLConnection) url
.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader isw = new InputStreamReader(in);
int data = isw.read();
while (data != -1) {
current += (char) data;
data = isw.read();
System.out.print(current);
}
// return the data to onPostExecute method
return current;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
} catch (Exception e) {
e.printStackTrace();
return "Exception: " + e.getMessage();
}
return current;
}
#Override
protected void onPostExecute(String s) {
Toast.makeText(Register.this, "success", Toast.LENGTH_SHORT).show();
Log.d("data", s.toString());
// dismiss the progress dialog after receiving data from API
try {
// JSON Parsing of data
JSONArray jsonArray = new JSONArray(s);
JSONObject oneObject = jsonArray.getJSONObject(0);
// Pulling items from the array
client = Integer.parseInt(oneObject.getString("client"));
staff = Integer.parseInt(oneObject.getString("staff"));
} catch (JSONException e) {
e.printStackTrace();
}
} }}
The logic in your code looks off to me. This is the pattern I usually follow when making a REST call from an activity using HttpURLConnection:
try {
String endpoint = "http://192.168.1.13:8080/digitaldisplay/s/m/data";
URL obj = new URL(endpoint);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST"); // but maybe you want GET here...
con.setConnectTimeout(10000);
con.setDoInput(true);
con.setDoOutput(true);
JSONObject inputJSON = new JSONObject();
inputJSON.put("Client_id", 1);
inputJSON.put("Staff_id", 2);
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
OutputStream os = con.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(inputJSON.toString());
writer.flush();
writer.close();
os.close();
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response);
} catch (SocketTimeoutException se) {
// handle timeout exception
responseCode = -1;
} catch (Exception e) {
// handle general exception
responseCode = 0;
}
The only major change in adapting the above code for GET would be that you wouldn't write your input data to the connection. Instead, you would just append query parameters to the URL. I am possibly guessing that you need POST here, since your URL doesn't have any query parameters in it.
I am trying to successfully send data across from an android app to a php web app and display that data and save into a mysql database. However i don't get an exception or anything just the data i send across does not get received on the server end. My code is below:
public void onClick(View view) {
String text = "None";
switch (view.getId()) {
case R.id.btnOne:
send();
text = "Response Submitted";
break;
case R.id.btnTwo:
text = "Two";
break;
case R.id.btnThree:
text = "Three";
break;
case R.id.btnFour:
text = "Four";
break;
}
Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
}
private void send() {
URL a = null;
try {
a = new URL("http://cce.swlgroup.com/json.php/");
} catch (Exception exception) {
exception.printStackTrace();
}
new URLTestTask().execute(a);
}
private class URLTestTask extends AsyncTask<URL, Integer, Void> {
#Override
protected void doInBackground(URL... urls) {
HttpURLConnection conn = null;
BufferedReader reader = null;
try {
URL url = new URL("http://cce.swlgroup.com/json.php/");
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
Log.e("", "" + conn.getResponseMessage());
conn.connect();
JSONObject obj = new JSONObject();
obj.put("Marge","Simpson");
HttpClient client = new DefaultHttpClient();
HttpGet post = new HttpGet(url.toURI());
post.setEntity(new ByteArrayEntity(obj.toString().getBytes("UTF8")));
post.setHeader("json",obj.toString());
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String responseBody = client.execute(post,
responseHandler);
HttpEntity ent = post.getEntity();
InputStream stream = ent.getContent();
String result = RestClient.convertStreamToString(stream);
BufferedReader red = new BufferedReader(new InputStreamReader(ent.getContent()));
String line;
StringBuilder lb = new StringBuilder();
while((line = red.readLine()) != null){
lb.append(red);
}
red.close();
Log.i("Read from server", result);
} catch (Exception e){
e.printStackTrace();
}finally {
if (conn != null)
conn.disconnect();
try{
if (reader != null)
reader.close();
} catch (Exception e){
e.printStackTrace();
}
}
return null;
}
}
my php code is below to get data and display:
$json = file_get_contents('php://input');
$obj = json_decode($json);
var_dump($obj);
var_dump($_POST);
var_dump($_GET);
HttpURLConnection conn = null;
BufferedReader reader = null;
try {
URL url = new URL("http://10.0.2.2/json.php/");
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
Log.e("", "" + conn.getResponseMessage());
conn.connect();
JSONObject obj = new JSONObject();
obj.put("Marge","Simpson");
HttpClient client = new DefaultHttpClient();
StringBuilder pat = new StringBuilder();
HttpGet post = new HttpGet(url.toURI());
post.setEntity(new ByteArrayEntity(obj.toString().getBytes("UTF8")));
post.setHeader("json", obj.toString());
post.setHeader("Content-Type", "application/json");
post.setHeader("accept-encoding","gzip, deflate");
post.setHeader("accept-language","en-US,en;q=0.8");
post.setHeader("FormData",obj.toString());
HttpResponse lazy = client.execute(post);
HttpEntity ent = lazy.getEntity();
String lb = EntityUtils.toString(ent);
pat.append(lb);
Log.i("Read from server", pat.toString());
} catch (Exception e){
e.printStackTrace();
}finally {
if (conn != null)
conn.disconnect();
try{
if (reader != null)
reader.close();
} catch (Exception e){
e.printStackTrace();
}
}
return null;
I made the change in accordance with that code but it doesnt seem to send a result across.
I have an application that post data to a php file in an online server. When the post is done i get a garbage of html code. In it says I have a php error and that is Invalid argument supplied for each() on line 33. However this problem does not occur if I run it in localhost. I don't understand why this problem is occuring. So someone please help me to solve it.
The following is my jsonparser Class
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getandpostJSONFromUrl(String url, String method,JSONArray name) {
// Making HTTP request
try {
// defaultHttpClient
if (method == "POST") {
HttpParams params = new BasicHttpParams();
//params.setParameter("data", auth);
HttpClient httpclient = new DefaultHttpClient(params);
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> postParams = new ArrayList<NameValuePair>();
postParams.add(new BasicNameValuePair("json", name.toString()));
for (NameValuePair nvp : postParams) {
String name2 = nvp.getName();
String value = nvp.getValue();
Log.d("NameValue pair content", ""+name2+""+value);
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParams,HTTP.UTF_8);
httpPost.setEntity(entity);
HttpResponse response = httpclient.execute(httpPost);
String responseBody = EntityUtils.toString(response.getEntity());
Log.d("",responseBody);
}
if (method == "GET") {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (method == "POST") {
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
} catch (Exception e) {
Log.e("Buffer error", "Buffer error" + e);
}
} else if (method == "GET") {
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
}
// return JSON String
return jObj;
}
}
The following is the php file on the server
<?php
header('Content-type: application/json');
/*define('DB_NAME', 'a1422982_sshop');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');*/
define('DB_NAME', 'onlineshop');
define('DB_USER', 'shop');
define('DB_PASSWORD', 'pass');
define('DB_HOST', 'mysql28.000webhost.com');
$link = mysql_connect(DB_HOST,DB_USER,DB_PASSWORD);
if(!$link){
die('could not connect: '.msql_error());
}
$db_selected=mysql_select_db(DB_NAME, $link);
if(!$db_selected){
die('Can not use '.DB_NAME.':'.mysql_error());
}
//var_dump(json_decode ($_POST['json'])));
if($_POST['json']){
$parsed = json_decode($_POST['json'],TRUE);
$i=0;
foreach ($parsed as $obj) {
$ProductName = $obj['Name'];
$ProductQuantity= $obj['Quantity'];
$sql="Update productlist Set Quantity='$ProductQuantity' where Name='$ProductName';";
$retval = mysql_query( $sql, $link );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
$i++;
echo $ProductName." ".$ProductQuantity;
}
}else{
echo "empty";
}
?>
there's a missing options on your HttpPost request set the entity metadata and the resulting entity as string.
In your java code you can do this:
Map<String, String> postData = new HashMap<String, String>();
postData.put("KEY", "yourvalue");
JSONObject holder = new JSONObject(postData);
StringEntity jsonStringEntity = new StringEntity(holder.toString());
httpost.setEntity(jsonStringEntity);
httpost.setHeader("Accept", "application/json");
httpost.setHeader("Content-type", "application/json");
in that way your PHP code could actually parse your post data since json_decode() expecting json as parameter.
I have developed an application, that has text view for display some Gujarati text from the JSON URL and data stored in PHP MySQL server database.
So, problem with display Gujarati font:
My code of JSON http is here:
public class CustomHttpClient {
public static final int HTTP_TIMEOUT = 30 * 1000;
private static HttpClient mHttpClient;
private static HttpClient getHttpClient() {
if (mHttpClient == null) {
mHttpClient = new DefaultHttpClient();
final HttpParams params = mHttpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
}
return mHttpClient;
}
public static String executeHttpPost(String url,ArrayList<NameValuePair> postParameters) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpPost request = new HttpPost(url);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(
postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent()));
// in = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8000);
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
Log.e("log_tag", "Error converting result "+e.toString());
e.printStackTrace();
}
}
}
}
and main activity code here:
desc_about=(TextView)v.findViewById(R.id.textdesc);
Typeface tf=Typeface.createFromAsset(getActivity().getAssets(),"Shruti.ttf");
desc_about.setTypeface(tf);
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("temple_id","2"));
String response = null;
try {
response = CustomHttpClient.executeHttpPost(
url_temple,postParameters);
String result = response.toString();
try {
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++)
{
JSONObject json_data = jArray.getJSONObject(i);
about_temple=json_data.getString("about_text");
}
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
try{
desc_about.setText(about_temple);
}
catch(Exception e){
Log.e("log_tag","Error in Display!" + e.toString());;
Toast.makeText(getActivity(), "error" + 2, 100).show();
}
}
catch (Exception e) {
Log.e("log_tag","Error in http connection!!" + e.toString());
Toast.makeText(getActivity(), "error" + 3, 100).show();
}
Try using utf-endcoding at the time of making JSON on php side and same way decode utf in android side. I solved it using this way in iOS app, Thanks
Try this solution
StringRequest stringRequest = new StringRequest(Request.Method.GET,"http://floming.com/shayri/guj_romanse.json", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
String str = "";
try {
str = new String(response.getBytes("ISO-8859-1"), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String decodedStr = Html.fromHtml(str).toString();