Android material design Programming Blog

Android AsyncTask to fetch PHP file without using any library

This tutorial is on, retrieving PHP file without using any library like volley or retrofit, To do that we are making use of Android AsyncTask and HttpURLConnection class.

Rather than using any library to fetch data from PHP Or JSON file, you can use a standard method of Android AsyncTask and HttpURLConection class. One advantage of using Android AsyncTask over any library is file size, using any library in your code puts an extra burden on your application in terms of application size.

I suggest you use AsyncTask when there is only a fewer request made to the server and in case of multiple requests, use volley or any other libraries.

Let’s see how to fetch data from PHP file using Android AsyncTask.

Download Code From Github


A sample PHP file.


  echo "Success! This message is from PHP";



The files involved are as follow. with Android AsyncTask

Here are the major steps involved.

  • Immediate after Activity is created an object of AsyncRetrieve class is created to carry out the Asynchronous task.
  • onPreExecute(), this method runs on UI thread. Here We are displaying a loading message.
  • doInBackground(Params...), invoked on the background thread immediately after
    onPreExecute() finishes executing. The receiving of data from PHP file using the HttpURLConnection class has done in this function.
  • onPostExecute(Result), collect the result from doInBackground(Params...) method. Here we are displaying data received from PHP file.
package com.androidcss.asyncexample;

import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    // CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
    public static final int CONNECTION_TIMEOUT = 10000;
    public static final int READ_TIMEOUT = 15000;
    TextView textPHP;

    protected void onCreate(Bundle savedInstanceState) {
        textPHP = (TextView) findViewById(;
        //Make call to AsyncRetrieve
        new AsyncRetrieve().execute();

    private class AsyncRetrieve extends AsyncTask<String, String, String> {
        ProgressDialog pdLoading = new ProgressDialog(MainActivity.this);
        HttpURLConnection conn;
        URL url = null;

        //this method will interact with UI, here display loading message
        protected void onPreExecute() {



        // This method does not interact with UI, You need to pass result to onPostExecute to display
        protected String doInBackground(String... params) {
            try {
                // Enter URL address where your php file resides
                url = new URL("");

            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                return e.toString();
            try {

                // Setup HttpURLConnection class to send and receive data from php
                conn = (HttpURLConnection) url.openConnection();

                // setDoOutput to true as we recieve data from json file

            } catch (IOException e1) {
                // TODO Auto-generated catch block
                return e1.toString();

            try {

                int response_code = conn.getResponseCode();

                // Check if successful connection made
                if (response_code == HttpURLConnection.HTTP_OK) {

                    // Read data sent from server
                    InputStream input = conn.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                    StringBuilder result = new StringBuilder();
                    String line;

                    while ((line = reader.readLine()) != null) {

                    // Pass data to onPostExecute method
                    return (result.toString());

                } else {

                    return ("unsuccessful");

            } catch (IOException e) {
                return e.toString();
            } finally {


        // this method will interact with UI, display result sent from doInBackground method
        protected void onPostExecute(String result) {

            if(result.equals("Success! This message is from PHP")) {
                // you to understand error returned from doInBackground method
                Toast.makeText(MainActivity.this, result.toString(), Toast.LENGTH_LONG).show();



XML file for

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android=""
    xmlns:tools="" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <TextView android:text="Something went Wrong!" android:layout_width="wrap_content"
        android:id="@+id/textPHP" android:textAppearance="?android:attr/textAppearanceLarge" />


Make sure you added, below marked code to your AndroidManifest file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android=""
    package="com.androidcss.asyncexample" >
    <uses-permission android:name="android.permission.INTERNET"/>
        android:theme="@style/AppTheme" >
        <activity android:name=".MainActivity" >
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />



Add yours

  1. hello, why it does not get all data of my url ?

  2. Thank-you so much Gururaj P Kharvi.

  3. Thank you very much! I was searching for this tutorial and none worked. Your code helped me out. Keep up the good work!

  4. How I connect my php file with my android project and where it put

  5. Hi, Gururaj P Kharvi

    I tried your tutorial, but there is something error.
    I use WAMP and Android Studio without emulator.

    The result of that statement above is 403 or HTTP_Forbidden.

    Please advice, sir.
    Thank you very much.

  6. Hi, I already tried Android to fetch PHP file without using any library more than 10times…
    However it appear unsuccessful toast message..
    Can I know any possibilities reason my project doesnt work?
    Really need help.
    Thank you in advance..

    • @mira
      you are getting ‘unsuccessful’ message because the URL you specified is not valid, enter your url(where your php file resides) in browser and check for whether address is valid. you can check above code for return "unsuccessful"; when it fails to connect.

      Let me know whether your problem solved or not. If you really require any help from my side then i assist you through TeamWeaver.

      • It work at last.. thank you so much..
        However, if I want to display information using php file, I should enter same word in
        Because when I tried to change the words at php file, it wont display php file text at android screen but it show in toast message. I dont really know how to change the code here..

        if(result.equals(“Success! This message is from PHP”)) {
        // you to understand error returned from doInBackground method
        Toast.makeText(MainActivity.this, result.toString(), Toast.LENGTH_LONG).show();

        Thank you for your respond. 🙂

        • @Mira

          In class which extends Android AsyncTask, I returned all exception and displayed them on Toast message because, you to understand what and where exactly error is occuring. Now, there is a no need of if statement, remove return statement from every catch block in your doInBackground() method or you can handle those error appropriately.

          Above code can be rewritten as


Leave a Reply

Your email address will not be published.


About | Policy | Disclaimer

Creative Commons LicenceUp ↑