I develop an android code for transmit and received between android apps and PHP. The received part which is based on JSON, is properly working. I have tested by set variable manually in PHP code. However, when I have posted the variable from android to php, it cannot receive it. Anyone can tell me the problem ?
#Override
protected String doInBackground(Void... params) {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username", <Your username here>));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(<Your URL to php file>);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
HttpResponse response = httpclient.execute(httppost); // Execute Post to URL
String st = EntityUtils.toString(response.getEntity()); // This is the result from php web
Log.d(TK_Configuration.TAG, "In the try Loop" + st); // Still executing
finalResult = st; // You should register a variable for finalResult;
} catch (Exception e) {
Log.d(TK_Configuration.TAG, "Connection error : " + e.toString());
}
return "OK";
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
// After that, you will have final result and process to do with it here
// Below is my simple code, please change it
if(finalResult.equals("1")){
Toast.makeText(context, context.getResources().getString(R.string.upload_bike_success), Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(context, context.getResources().getString(R.string.upload_bike_fail), Toast.LENGTH_SHORT).show();
}
// End
}
Please try this, and one more point, you should use Gson library to decode JSON quickly to Java Object after you got JSON string from server.
Note: Replace TK_Configuration.TAG << by your TAG.
you have commented this line it means you are not passing values from Android
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
remove comment from this line.
One more thing, you are passing username but from php you are trying to fetch value as $user = $_POST['name'];, both name must be same.
Related
i try to send information from android app to server to save in data base my code runs correctly but no data saved in database and i didn't get any response. i don't know where is the mistake in my code
private class postData extends AsyncTask<String, Void, String> {
// private final ProgressDialog dialog = ProgressDialog.show(getActivity(), "",
// "Saving data to server. Please wait...", true);
#Override
protected String doInBackground(String... params) {
// perform long running operation operation
// SharedPreferences settings = context.getSharedPreferences(PREFS_FILE, 0);
//String server = settings.getString("server", "");
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://phone.com/request_job");
String json = "";
String responseStr="";
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("ticket", "welcome"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
try {
httpclient.execute(httppost);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
// Execute HTTP Post Request
// ResponseHandler<String> responseHandler=new BasicResponseHandler();
//String responseBody = httpclient.execute(httppost, responseHandler);
// if (Boolean.parseBoolean(responseBody)) {
// dialog.cancel();
// }
HttpResponse response = httpclient.execute(httppost);
responseStr = EntityUtils.toString(response.getEntity());
} catch (IOException e) {
// TODO Auto-generated catch block
Log.i("HTTP Failed", e.toString());
}
return responseStr;
}
protected void onPostExecute(String responseStr) {
super.onPostExecute(responseStr);
Toast.makeText(getActivity(),responseStr,Toast.LENGTH_LONG).show();
if(responseStr.equals("true")){
// Update your Button here
Toast.makeText(getActivity(),"donefinally",Toast.LENGTH_LONG).show();
}
}
}
my code in server
public function check_user(Request $request){
$ticket = new ticket;// this line responsible to set data in database
$ticket->ticket = $request->ticket;
return response()->json(['data','true']);
}
}
In your server, do
$ticket = new ticket;// this line responsible to set data in database
$ticket->ticket = $request->ticket;
$ticket->save(); //<-- this line will save
Or in one go
$ticket = Ticket::create([
'ticket' => $request->ticket
]);
...
Now, make sure you call your ticket class properly. Not sure whether it's capital T (Ticket) or lowercase (ticket).
Edit
Since it's not working, you need to debug it step by step to see where the bottleneck is. First, in your function, simply do
return response()->json($request->ticket);
//This will prove that the request makes it to the server
Once you are sure you request makes it to the server, try to manually save something like
Ticket::create([
'ticket' => 'random string'
]);
You can call this function directly from your browser to test if it works. If nothing is saved in the db, make sure you have a $fillable array in your model and that you can connect properly to the db.
I am a newbie to android development so please be patient with me.
I am trying to post user id and password to a PHP page and return data (page working fine, tested and returns Json data).
I followed online guides and had similar problem to:
How to send data to a website using httpPost, app crashes
So I followed what was said in the following Answer within the above post
https://stackoverflow.com/a/18588948/3415061
No more Errors , but now how do I control what happens after data returned and if valid how do I go to the next screen and display it?
The following function executes the request but how I do I get the response to the screen if valid or not.
#Override
protected Boolean doInBackground(Void... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.blag.com/blag.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("acc", "blag"));
nameValuePairs.add(new BasicNameValuePair("usr", "blag"));
nameValuePairs.add(new BasicNameValuePair("pass", "blag"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
return true;
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return false ;
}
Or am I suppose to access the response in here, but I tried to launch another screen from here but I got errors.
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
if(result){
//successful request
}else{
//error in request response
}
// msgTextField.setText(""); // clear text box
}
Am I taking the correct approach to doing this?
Thanks in advance!!!
new code:
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(result=="HEllO"){
//successful request
Intent dashboard = new Intent(getApplicationContext(), MainOrder.class);
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
//userFunction.logoutUser(getActivity().getApplicationContext());
}else{
//error in request response
}
// msgTextField.setText(""); // clear text box
}
error on GetApplicationContext:
The method getApplicationContext() is undefined for the type NetRequestAsync
and error on line Command StartActivity
The method startActivity(Intent) is undefined for the type NetRequestAsync
If this code is inside an Activity of name, let's say MyCoolActivity, then you can access those methods with MyCoolActivity.this.getApplicationContext() and MyCoolActivity.this.startIntent()
I have connected database with phpliteadmin using xampp on localhost. Now I have to retrieve data from localhost and also to update it.. So any 1 can help me out from this problem..??
ok i have a function that sends some data to your local host and retrieve some data from there
use this method for communication :-
public void postData() throws Exception {
postData=et.getText().toString(); //some value
HttpClient httpclient = new DefaultHttpClient(); // connection
HttpPost httppost = new HttpPost("http://192.168.1.21/default.php"); //ip of your local host and php file!
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("msg", ""+str));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,HTTP.UTF_8));
ResponseHandler<String> responseHandler=new BasicResponseHandler(); // to get the response printed there
String responseBody = httpclient.execute(httppost, responseHandler); // here we are recieving values.
Toast.makeText(this, responseBody, Toast.LENGTH_LONG).show();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
}
}
and you can use this php coding to send and retrieve values :-
<?php
include ('MCrypt.php'); //this my encryption example
$thename=$_POST["msg"]; //get values from there using post and "msg" must be same on both side!
$mcrypt = new MCrypt();
$decrypted = $mcrypt->decrypt($thename);
echo("Your Encrypted String:--".$thename."\n"); // this line will be sent to android and will be recived in String Response;
echo("Your Decrypted String:--".$decrypted);
?>
What I try to do
Hello Guys,
I try to create a login for my server, that I can access the data on it over my app. For this i created a Methode called 'public void doLogin(final String username, final String password)' . In this Methode I start a Thread in which I post the username and password to my server. Now to problem starts. When I do the post my server can't handle my post which looks like this: '"username="+username+"&password="+password'.
To try if its a serverside problem (infact its not) I made a post over 'curl -d' with the same parameters and I get a response without any problems.
For your information the server runs on Ruby3
Question
How do I need to change my Post to the server that it can handle the data I send. By the way the string I post must look exactly like that: '"username="+username+"&password="+password //this means username=LEUSER&password=LEPASS'
Please tell me what I need to change, some code snippets or tutorials would be great. Down here you find the importrent codesnippets of the doLogin Methode
Code
public void doLogin(final String username, final String password) {
Thread t = new Thread() {
public void run() {
String URL = "http://192.168.110.126:3000/sessions.json"; //für momentane testzwecke
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse response;
try {
HttpPost post = new HttpPost(URL);
StringEntity se = new StringEntity("username="+username+"&password="+password);
post.setEntity(se);
response = client.execute(post);
if (response != null) {
//response handling
handler.sendEmptyMessage(0);
}
} catch (Exception e) {
e.printStackTrace();
Log.e("DataHandler", "URLConnection-Error" + e);
}
}
};
t.start();
}
Please Guide me Regarding This.
Your code looks like you are sending a html form. In fact curl adds a content-type (with value application/x-www-form-urlencoded) to the http header if you use the -d option.
So try to add the header field like this:
HttpPost post = new HttpPost(URL);
post.addHeader("Content-Type","application/x-www-form-urlencoded");
...
What you need to change is the String entity part. You should change with the following;
ArrayList<NameValuePair> requestParameters = new ArrayList<NameValuePair>();
requestParameters.add(new BasicNameValuePair("username", username));
requestParameters.add(new BasicNameValuePair("password", password));
username & password are the variables that are input on the program.
Lastly, if you forget to set permission it also won't work. You need to set android.permission.INTERNET
I'm trying to increase my knowledge to Android and trying to code a small app for my personal needs.
I'm trying to post data via the HTTP Post method on a test server.
The request is sent ok, but now, I'm trying to display the response, which is an HTML page with the dump of my request.
Here is an extract of my code, it is basically a few EditText fields, and button that sends the request.
The following code is the listener for that button.
validateButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://posttestserver.com/post.php?dump&html&dir=mydir&status_code=200");
try {
// Gathering data
String value01 = nb01Spinner.getSelectedItem().toString();
String value02 = nb02EditText.getText().toString();
String value03 = nb03EditText.getText().toString();
String value04 = nb04EditText.getText().toString();
// Add data to value pairs
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(04);
nameValuePairs.add(new BasicNameValuePair("test01", value01));
nameValuePairs.add(new BasicNameValuePair("test02", value02)); //
nameValuePairs.add(new BasicNameValuePair("test03", value03));
nameValuePairs.add(new BasicNameValuePair("test04", value04));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
I'm not sure if I need to create another Activity or not... I suppose I also have to create a webview aswell, but I'm a bit lost. For now the "raw" HTML would be fine, but afterwards I will need to parse the data, and extract only the strings I need.
So I would need help (an a good and simple example !)
Thank you.
String ret = EntityUtils.toString(response.getEntity());
Maybe this will help?
Very simple approach is Take textview the way you have taken button widget. and what ever response you got set in the textview. you will be able to see the response. else use the Log to log your response in the logcat.
This is how you get the Http response :
byte[] buffer = new byte[1024];
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://www.rpc.booom.com");
postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("params","1"));
//.......
httppost.setEntity(new UrlEncodedFormEntity(postParameters));
HttpResponse response = httpclient.execute(httppost);
Log.w("Response ","Status line : "+ response.getStatusLine().toString());
buffer = EntityUtils.toString(response.getEntity()).getBytes();
I am using:
Log.d("log_response", response.getStatusLine().toString());