How do I send POST information from my android application to a PHP website

137 views Asked by At

I've got a form built in my android layout, and have an activity that takes some text from that form and attaches it to a variable.

I also have a PHP form that can handle a POST variable containing the text when it arrives.

Seeing that HttpClient is deprecated (leaving a slew of dead stackOverflow answers in it's wake), what is the newest way to send the POST?

I'm not looking for anything complicated - just "Here's how you connect and send a solitary variable."

UPDATE: I was hoping for an answer that doesn't require me to use any outside classes. Doesn't android have this capability independently?

2

There are 2 answers

0
Kingxlayer On

You can use Android Async HTTP Client

http://loopj.com/android-async-http/

Gradle

compile 'com.loopj.android:android-async-http:1.4.9'

static HTTP client

public class RestClient {

    public static final String TAG = RestClient.class.getSimpleName();

    private static final String BASE_URL = "http://your-site.com/api/v1/whatever";

    private static AsyncHttpClient client = new AsyncHttpClient();

    public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
        client.get(getAbsoluteUrl(url), params, responseHandler);
    }

    public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
        client.post(getAbsoluteUrl(url), params, responseHandler);
    }

    private static String getAbsoluteUrl(String relativeUrl) {
        return BASE_URL + relativeUrl;
    }
}    

Client code

...
RequestParams params = new RequestParams();
params.put("THE_KEY", "THE_VALUE");
...

AsyncHttpClient client = new AsyncHttpClient();
client.post("YOUR_URL", new AsyncHttpResponseHandler() {

@Override
public void onStart() {
    // called before request is started
}

@Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
    // called when response HTTP status is "200 OK"
}

@Override
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
    // called when response HTTP status is "4XX" (eg. 401, 403, 404)
}

@Override
public void onRetry(int retryNo) {
    // called when request is retried
}
...
4
Charuක On

Here is a small example to connect and send a solitary variable

dependencies {
     compile 'com.squareup.okhttp3:okhttp:3.1.2'
    }

then you can get these imports

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;

AsyncTask

 private class NotifyPassengerDriverArrival extends AsyncTask<Void, Void, String> {

        private final String url = Constants.API_PATH + "notify_driver_location?token=" + Constants.TOKEN;
        private final OkHttpClient client = new OkHttpClient();

        @Override
        protected void onPreExecute() {
         super.onPreExecute();
        }

        @Override
        protected String doInBackground(Void... voids) {

            try {
                FormBody formBody = new FormBody.Builder()
                        .add("passenger_id", passengerID)
                        .build();
                Request.Builder builder = new Request.Builder();
                builder.url(url);
                builder.post(formBody);
                Request request = builder.build();

                okhttp3.Response response = client.newCall(request).execute();
                if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

                if (response.code() != 200) {
                    return null;
                }

                return "success";
            } catch (Exception e) {
                return null;
            }

        }


        @Override
        protected void onPostExecute(String data) {
            if (data == null) {
                return;
            }
            else {
                Toast.makeText(ReadyToStartTaxiJourneyActivity.this, "You are almost come to pickup location.", Toast.LENGTH_LONG).show();

            }
           super.onPostExecute(data);
        }
    }

Btw SO answers are not dead! If so ..may be that's because you only dig the grave yard!