Tuesday, November 1, 2016

[Android][php] Example code for using okhttp to send post repuest and get response from a php webpage

Step1 - Add okhttp as dependencies in yout project

Firstly, you needed to add dependencies your build.gradle in your module and check "Sync Now" next to the line "Gradle files have changed since last project sync. A project sync may be neccessary for the IDE to work properly." with yellow background.


dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.squareup.okhttp3:okhttp:3.2.0'
}

Step 2 - Create php file

Create a php file named "test.php", for my case i placed it at C:\xampp\htdocs\fcm in windows platform.
<?php
echo "Hello World : ";
if(isset($_POST['test'])) echo $_POST['test'];
?>

Step 3 - Make request and get feedback in your android project

Make request in AsyncTask or Thread, to make it looks simple i put that in a Thread (but using Thread in android may not is the good practice).
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Thread t = new Thread(new Runnable(){
            @Override
            public void run() {
                OkHttpClient client = new OkHttpClient();
                RequestBody body = new FormBody.Builder()
                        .add("test","HAHA")
                        .build(); //Create request body

                Request request = new Request.Builder()
                        .url("http://192.168.232.45/fcm/test.php")
                        .post(body)
                        .build(); //create request

                try {
                    //Send request and save response
                    Response response = client.newCall(request).execute();
                    //Show response
                    Log.d("dump","dump:"+response.body().string());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        t.start();
    }
}

Reference

https://square.github.io/okhttp/3.x/okhttp/okhttp3/ResponseBody.html

No comments :

Post a Comment