Sending send data through URL parameters in Android - php

I'm trying to make an app when users fill form, and click send button, to send informations through url parametrs like :
localhost/my.php?param1=Name&param2=SureName
I have read through internet about it, but can't get it, I found some examples but they tell how to pass through Json, I want just to send through link. (I think is easiest way )
My php code is:
<?php
require "connection.php";
if (!isset($_GET['param1'])) {
echo '<p align="center"> No data passed!</p>"';
}
if (strcmp($_GET['param1'],'FirstParam')== 0)
{
$sql= "Query HERE TO ADD INTO DB";
mysqli_query($connection,$sql);
if ($connection->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $connection->error;
}
mysqli_close($connection);
}
Any help will be appreciated.

I recommend to have a look on OkHttp. It is an easy library to send HTTP requests in whatever way you like. On Vogella you can also find an example of sending a GET request with additional parameters. Basically it looks like this
HttpUrl.Builder urlBuilder = HttpUrl.parse("https://api.github.help").newBuilder();
urlBuilder.addQueryParameter("v", "1.0");
urlBuilder.addQueryParameter("user", "vogella");
String url = urlBuilder.build().toString();
Request request = new Request.Builder()
.url(url)
.build();
And after that you need to send your request (asynchronously) with the help of the OkHttpClient like this
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(Call call, final Response response) throws IOException {
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
} else {
// do something wih the result
}
}
(Code was taken from Vogella)

Related

Retrofit Post Data is not received by PHP

i want to update a table by using retrofit, so i have an API as follows
public interface StRegAPI {
#FormUrlEncoded
#POST("/stdreg.php")
public void regStudent(
#Field("stdid") String stdid,
#Field("stdpass") String stdpass,
#Field("stdadd") String stdadd,
#Field("stdphn") String stdphn,
#Field("stdemail") String stdemail,
Callback<Response> callback);
}
where my call back implementation is
StRegAPI api = adapter.create(StRegAPI.class);
//Defining the method insertuser of our interface
api.regStudent(
//Passing the values by getting it from editTexts
rn_list.getSelectedItem().toString(),
etstpass.getText().toString(),
etstad.getText().toString(),
etstphn.getText().toString(),
etstemail.getText().toString(),
//Creating an anonymous callback
new Callback<Response>() {
#Override
public void success(retrofit.client.Response result, retrofit.client.Response response) {
//On success we will read the server's output using bufferedreader
//Creating a bufferedreader object
BufferedReader reader = null;
//An string to store output from the server
String output = "";
try {
//Initializing buffered reader
reader = new BufferedReader(new InputStreamReader(result.getBody().in()));
//Reading the output in the string
output = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
//Displaying the output as a toast
Toast.makeText(StudReg.this, output, Toast.LENGTH_LONG).show();
}
#Override
public void failure(RetrofitError error) {
//If any error occured displaying the error as toast
Toast.makeText(StudReg.this, error.toString(),Toast.LENGTH_LONG).show();
}
}
);
}
and my PHP file is
<?php
//checking if the script received a post request or not
if($_SERVER['REQUEST_METHOD']=='POST'){
//Getting post data
$stdid=$_POST['stdid'];
$stdpass = $_POST['stdpass'];
$stdadd = $_POST['stdadd'];
$stdphn = $_POST['stdphn'];
$stdemail=$_POST['stdemail'];
//checking if the received values are blank
if($stdid == '' || $stdpass== '' || $stdad == '' || $stdemail=='' || $stphn==''){
//giving a message to fill all values if the values are blank
echo 'please fill all values';
}else{
//If the values are not blank
//Connecting to our database by calling dbConnect script
require_once('connection.php');
//Creating an SQL Query to insert into database
//Here you may need to change the retrofit_users because it is the table I created
//if you have a different table write your table's name
//This query is to check whether the username or email is already registered or not
$sql = "SELECT * FROM student WHERE stud_id=$stdid";
//If variable check has some value from mysqli fetch array
//That means username or email already exist
$check = mysqli_fetch_array(mysqli_query($con,$sql));
//Checking check has some values or not
if(!(isset($check))){
//If check has some value that means username already exist
echo 'studentid does not exist';
}else{
//If username is not already exist
//Creating insert query
$sql = "UPDATE student set password='$stdpass', addrs='$stdad',phn_no=$stdphn,email='$stdemail' WHERE stud_id=$stdid";
//Trying to ins db
if(mysqli_query($con,$sql)){
//If inserted successfully
echo 'successfully registered';
}else{
//In case any error occured
echo 'oops! Please try again!';
}
}
//Closing the database connection
mysqli_close($con);
}
}else{
echo 'error';
}
but in PHP it is not receiving the data at all. in postman also i tested it is specifying that undefined index stdid similarly for all the data fields. Please help me out. thanks a million in advance
Remove Callback<Response> callback); from your request regStudent().
So your API request class would be below
public interface StRegAPI {
#FormUrlEncoded
#POST("/stdreg.php")
public void regStudent(
#Field("stdid") String stdid,
#Field("stdpass") String stdpass,
#Field("stdadd") String stdadd,
#Field("stdphn") String stdphn,
#Field("stdemail") String stdemail);
}
You have to enqueue your request then only it's will send data to server.
Call<Response> call =api.regStudent(
//Passing the values by getting it from editTexts
rn_list.getSelectedItem().toString(),
etstpass.getText().toString(),
etstad.getText().toString(),
etstphn.getText().toString(),
etstemail.getText().toString());
call.enqueue(new Callback<Response>() {
#Override
public void onResponse(Response<Response> response) {
if (!response.isSuccess()) {
Log.d(LOG_TAG, "No Success");
}
}
#Override
public void onFailure(Throwable t) {
// api failed
}
});
I hope it's would be helpful

retrofit 1.9 keeps calling failure and returns null body

I am trying to communicate with my php webservice (google app engine), but it keeps responding with body as null and also triggering the failure() method of retrofit (callback).
I get the following error message in failure(), when debugging it:
retrofit.RetrofitError: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $
First here is the code where I trigger the request to my webservice:
WebServiceManager.getInstance().registerRequest(email, password, username, firstname, lastname, new Callback<RegisterResponse>() {
#Override
public void success(RegisterResponse registerResponse, Response response) {
Toast.makeText(context, registerResponse.getToken() + "", Toast.LENGTH_LONG).show();
}
#Override
public void failure(RetrofitError error) {
Toast.makeText(context,"error ", Toast.LENGTH_LONG).show();
}
});
And here is my WebServiceManager class for managing the requests and responses:
http://pastebin.com/Q8bzqQ0M
And the model classes for the requests and responses:
http://pastebin.com/aB98Yiua
This is how my json request looks like:
{
data{
"email": "regd#rgersf.dk",
"firstname": "regdrgersf",
"lastname": "regdrgersf",
"password": "hejhejhej",
"username": "regdrgersf"
}
}
I also think it is relevant to include the part where I receive the request on my webservice:
<?php
require '../functions/db.php';
$data = getJsonRequest();
$email = $data['data']['email'];
$password = $data['data']['password'];
$username = $data['data']['username'];
$firstname = $data['data']['firstname'];
$lastname = $data['data']['lastname'];
$facebookID = $data['data']['facebookID'];
$dbClass = new DBClass();
$result = $dbClass->register($email, $password, $username, $firstname, $lastname, $facebookID);
$response = array();
if ($result == $dbClass->error_input || $result == $dbClass->error_email_exists || $result == $dbClass->error_unknown || $result == $dbClass->error_db_connection) {
$response['status'] = false;
$response['error'] = $result;
} else {
$response['status'] = true;
$response['token'] = $result;
}
sendJsonResponse($response);
?>
And the function "sendJsonResponse($response)" for sending the response:
function sendJsonResponse($response) {
header('HTTP/1.1 200 OK');
header('Content-type: application/json');
echo json_encode($response);
}
I can't figure out if the problem is somewhere in my java (android) code and retrofit or if i'm doing something wrong on the webserver.
Any help will be greatly appreciated.
I found a way to fix it myself, so I think I should post my solution here so that it might help others.. even though I am not sure why my first solution didn't work.
By removing the annotation #FormUrlEncoded and changing #Field('data') to #Body, it actually worked. Så the interface looks like this now.
private interface webServiceInterface {
#POST(WebServiceManager.REQUEST_REGISTER)
void register(#Body RegisterRequest registerRequest, Callback<RegisterResponse> response);
}
Anyways, I really appreciate all the help I got from people here.

trying to get array from php and store it in java,android

ive got a php file that connect to database and fetches data, now i want this data to be sent to my java code and be stored as an array, for connecting to php and retriving results i am using AsyncHttpClient
now in AsyncHttpClient their is a func onSucess that takes a string value as its parameter, soo anything coming from php is stored as string. i want it to be array..
please suggest me a way, either to get an array instead of string
following is my code.
public void func3(View view)throws Exception
{
AsyncHttpClient client = new AsyncHttpClient();
RequestParams rp = new RequestParams();
rp.put("pLat", "select * from iwmp_state");
client.post("http://10.0.2.2/conc2.php", rp, newAsyncHttpResponseHandler() {
public final void onSuccess(Array response) {
// handle your response here
//tx.setText(response.toString());
}
#Override
public void onFailure(Throwable e, String response) {
// something went wrong
tx.setText(response.toString());
}
});
}
and ive got a php file which echos an array $row
<?php
// attempt a connection
$dbh = pg_connect("host=10.22.35.11 dbname=iwmp_dev2 user=postgres ");
if (!$dbh) {
die("Error in connection: " . pg_last_error());
}
// execute query
$sql = $_POST['pLat'];
$result = pg_query($dbh, $sql);
if (!$result) {
die("Error in SQL query: " . pg_last_error());
}
$array = array();
// iterate over result set
// print each row
while ($row = pg_fetch_array($result)) {
$i++;
echo $row[0];
}
// free memory
pg_free_result($result);
// close connection
pg_close($dbh);
?>
what php echos is array and what onSuccess takes as parameter is string. what to do!
Here, i am just showing simple demo.You have to update as per your requirement.
PHP Side
Creating simple PHP Array , For more detail click here
<?php
$cars=array("Volvo","BMW","Toyota");
$arrlength=count($cars);
for($x=0;$x<$arrlength;$x++)
{
echo $cars[$x];
echo "<br>";
}
echo json_encode($cars);
exit;
?>
Android Side
Now How to read PHP array inside in android ?
String String_Response = ""; // this is your web response
Create a ArrayList.
ArrayList<String> User_List = new ArrayList<String>();
try
{
JSONArray jArray = new JSONArray(String_Response);
for (int i = 0; i < jArray.length(); i++)
{
JSONObject json_data = jArray.getJSONObject(i);
User_List.add(json_data.getString("your_json_obj"));
}
}
catch (Exception e)
{
Log.e(TAG, "" + e);
}
Also check out below link in that you will get more idea how to send and receive data from android to php.
Android + PHP Communication Example
It is hard for me to understand what you wish to achieve, but perhaps I can help a little with:
Implode your php array into a string (http://php.net/manual/en/function.implode.php) then at least you can see what you are returning and perhaps re-process it client side?
got it, what we can do is to use a IMPLODE func in our php, and add (,) after every array value
and then let it be passed as string.
after getting it in java code use. split(",") func of String and store them in an array.
working fine for me. no json needed :P

Socket php server not showing messages sent from android client

Hi I am a newbie in these kind of stuff but here's what i want to do.
I am trying to implement a chat application in which users will send their queries from the website and as soon as the messages are sent by the website users.It will appear in the android mobile application of the site owner who will answer their queries .In short I wanna implement a live chat.
Now right now I am just simply trying to send messages from android app to php server.
But when I run my php script from dreamweaver in chrome the browser keeps on loading and doesn't shows any output when I send message from the client.
Sometimes it happened that the php script showed some outputs which I have sent from the android(client).But i don't know when it works and when it does not.
So I want to show those messages in the php script as soon as I send those messages from client and vice versa(did not implemented the vice versa for client but help will be appreciated).
Here's what I've done till now.
php script:
<?php
set_time_limit (0);
$address = '127.0.0.1';
$port = 1234;
$sock = socket_create(AF_INET, SOCK_STREAM, 0);
socket_bind($sock, $address, $port) or die('Could not bind to address');
socket_listen($sock);
$client = socket_accept($sock);
$welcome = "Roll up, roll up, to the greatest show on earth!\n? ";
socket_write($client, $welcome,strlen($welcome)) or die("Could not send connect string\n");
do{
$input=socket_read($client,1024,1) or die("Could not read input\n");
echo "User Says: \n\t\t\t".$input;
if (trim($input) != "")
{
echo "Received input: $input\n";
if(trim($input)=="END")
{
socket_close($spawn);
break;
}
}
else{
$output = strrev($input) . "\n";
socket_write($spawn, $output . "? ", strlen (($output)+2)) or die("Could not write output\n");
echo "Sent output: " . trim($output) . "\n";
}
}
while(true);
socket_close($sock);
echo "Socket Terminated";
?>
Android Code:
public class ServerClientActivity extends Activity {
private Button bt;
private TextView tv;
private Socket socket;
private String serverIpAddress = "127.0.0.1";
private static final int REDIRECTED_SERVERPORT = 1234;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bt = (Button) findViewById(R.id.myButton);
tv = (TextView) findViewById(R.id.myTextView);
try
{
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
socket = new Socket(serverAddr, REDIRECTED_SERVERPORT);
}
catch (UnknownHostException e1)
{
e1.printStackTrace();
}
catch (IOException e1)
{
e1.printStackTrace();
}
bt.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try
{
EditText et = (EditText) findViewById(R.id.EditText01);
String str = et.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
out.println(str);
Log.d("Client", "Client sent message");
}
catch (UnknownHostException e)
{
tv.setText(e.getMessage());
e.printStackTrace();
}
catch (IOException e)
{
tv.setText(e.getMessage());
e.printStackTrace();
}
catch (Exception e)
{
tv.setText(e.getMessage());
e.printStackTrace();
}
}
});
}
}
I've just pasted the onclick button event code for Android.Edit text is the textbox where I am going to enter my text.
The ip address and port are same as in php script.
I'd recommend using an event driven framework for handling your connections.
There's a fairly decent example called React but it has tons of other stuff in there you'll probably want to strip out so your app doesn't depend on hundreds of external components.
React uses a message loop based on libevent if you have it installed, or stream_select otherwise.
You handle events with closures, something like:
$client->on('read', function($data) use ($client) {
$client->onRead($data);
});
With this you will be able to handle lots of simultaneous connections, and it will not tie up all of your CPU.
Your code will be executed when something happens.
If nothing else, have a look at how it works, you'll get a better understanding of how to create a non-blocking event driven socket server.
First of all - your server will handle only one client connection at a time, which doesn't makes sense for chat.
I can't see how you deal with socket connection on Android side but anyway it will not allow you to connect again as long as your script execution will not execute "socket_accept()" and wait for connection.
You should run 1 loop process to grab new client connections and fork into separate process each connected client.
Take look at my same lightweight PHP server I wrote here which is based on the same principle:
https://github.com/webdevbyjoss/Aaaaa---space-ships-combat-multiplayer-game/blob/master/server/server.php
Ignore the Websockets related "doHandshake()" and "WebSocketFrame::decode/WebSocketFrame::encode" but you should be OK with the rest.
Generally it runs the loop
while (true)
if (($msgsock = socket_accept ( $sock )) === false) {
echo "socket_accept() failed: reason: " . socket_strerror ( socket_last_error ( $sock ) ) . "\n";
break;
}
// We got a client connected, lets process it in separate thread
if (($pid = pcntl_fork()) === -1) {
echo "pcntl_fork() failed. Make sure you are on Linux sustem, but not on Windows\n";
break;
}
if (!$pid) { // client
handleClient($msgsock);
exit();
}
// parent server will wait to accept more clients connections in new loop
}
And inside handleClient() function you should have a separate loop to communicate with the client.
while (true) {
if (false === ($buf = socket_read ( $msgsock, 2048, PHP_BINARY_READ ))) {
echo "socket_read() failed: reason: " . socket_strerror ( socket_last_error ( $msgsock ) ) . "\n";
return;
}
if (empty($buf)) { // do disconnection check
echo "Client disconnected\n";
return;
}
// -------------------------------------------------------------
// PUT YOUR BUSINESS LOGIC HERE
// TO HANDLE MESSAGES OF THE CHAT AND GENERATE RESPONSE TO USER
// I RECOMMEND TO USE SOMETHING LIKE MEMCACHE/REDIS/MONGO/MYSQL/TXT-FILES
// FOR MULTIPROCESS DATA INTERCHANGE
// -------------------------------------------------------------
// transfer data to client
socket_write($msgsock, $returnText, strlen($returnFrame));
}
socket_close ( $msgsock );
Have you tried adding '\r\n' into value of EditText before sending to server yet? I think the problem isn't connection between client and server because it doesn't show error when connection fail. Maybe in your case socket_read($client,1024,1) must stop reading at a '\r\n'.
Update: Your local ip maybe cause connection error. Have a look at this link
Your address 127.0.0.1 will resolve to the machine the code is running on. So the app actually tries to connect to itself. type ipconfig /all on the MSDOS console and use that address instead.

RequestBuilder returning null

I have the following problem.
I created a class to take care of all calls to a database.
I'm using RequestBuilder on the front end of GWT to send a HTTP GET request.
public String getDadosGET(String phpFilePath) {
rb = new RequestBuilder(RequestBuilder.GET, phpFilePath);
rb.setHeader(header, headerValue);
try {
response = rb.sendRequest(null, new RequestCallback() {
#Override
public void onResponseReceived(Request request, Response response) {
text = response.getText();
}
#Override
public void onError(Request request, Throwable exception) {
}
});
} catch (RequestException e) {
e.printStackTrace();
}
return text;
}
Now If I output the text inside the onResponseReceived method, It's not null.
If done right before return text, it's null.
What I need is to force the program to get the data first, then return the method.
Thanks.
I think you haven't quite understood the concept of asynchronous calls. Check out the this article.
I don't think there's a way of making a GWT call synchronously, which is what you seem to want.

Categories