2

I have created one api in local host using php. This as I test in postman its working well but when I am calling in the url from android its giving an exception of socket connection time out.

Its ampps server, not able to connect.

This is my php script:

    <?php

//echo error
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
ini_set('display_errors', '1');

// require database
require 'database.php';

//get file input
$jsonText = file_get_contents('php://input');

//check params in file
if (empty($jsonText)) {
    $response = array("status" => -1, "message" => "Empty request");
    die(json_encode($response));
}

try{

//decode params in json
$json = json_decode($jsonText);
$mobile_no = $json->mobile_no;
$device_id = $json->device_id;

//init database connection
$database = new Database(Constants::DBHOST, Constants::DBUSER, Constants::DBPASS, Constants::DBNAME);
$dbConnection = $database->getDB();

//query to insert device

$statement = $dbConnection->prepare("INSERT INTO data(mobile_number, device_id)
    VALUES(:mobile_no, :device_id)");
$statement->execute(array(
    "mobile_no" => $mobile_no,
    "device_id" => $device_id
));
    $newId = $dbConnection->lastInsertId();

    if($newId != null)
    {
        $response = array("status" => 1, "message" => "Success");
        die(json_encode($response));
    }
}
catch(PDOException $e) {
    echo $e->getMessage();
}

Constants:

<?php

class Constants
{
    const DBNAME = 'UserDevices';
    const DBUSER = 'fsdfsf';
    const DBPASS = 'fsdfsdfs';
    const DBHOST = '192.168.44.1';
}

?>

database

    <?php
require 'constants.php';

class Database
{

    private $dbhost;
    private $dbuser;
    private $dbpass;
    private $dbname;


    function Database($dbhost, $dbuser, $dbpass, $dbname)
    {
        $this->dbhost = $dbhost;
        $this->dbuser = $dbuser;
        $this->dbpass = $dbpass;
        $this->dbname = $dbname;

    }

    function getDB()
    {

        $mysql_conn_string = "mysql:host=$this->dbhost;dbname=$this->dbname;charset=utf8";

        try {
            $dbConnection = new PDO($mysql_conn_string, $this->dbuser, $this->dbpass);
            $dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch (PDOException $ex) {

            echo($ex->getMessage());
        }

        return $dbConnection;
    }
}

?>

android

    String token = tokenPreference.getString("token","");

    if(!token.equals("")) {
        //String cno=preferences.getString("cono",null);
        String[] keys = new String[] {"mobile_no", "device_id"};
        String[] values = new String[] {preferences.getString(Const.DRIVER_MOBILE_NUMBER,""), token};

        final String jsonRequest = SecondUtils.createJsonRequest(keys, values);

        String URL = "http://192.168.44.1/fuelOneTest/insertDevice.php";



        new WebserviceCall(MainDriver.this, URL, jsonRequest, "Loading", true, new AsyncResponse() {
            @Override
            public void onCallback(String response) {
                Log.d("myapp", response);

                //     Toast.makeText(RegisterDriver.this, model.getResponse_desc(), Toast.LENGTH_SHORT).show();

                try {
                    JSONObject jsonObject = new JSONObject(response);

                    // change below condition to 0.. for testing it change to 1
                    if (jsonObject.get("message").equals("Success")) {

                        Log.d("DeviceToken", "Device token inserted.");

                    } else {

                    }
                }catch (JSONException je)
                {
                    je.printStackTrace();
                }
            }
        }).execute();
    }

public class WebserviceCall extends AsyncTask<Void,Void,String> {
// interface for response

AsyncResponse delegate;
private final MediaType URLENCODE = MediaType.parse("application/json;charset=utf-8");
ProgressDialog dialog;
Context context;
String dialogMessage;
boolean showDialog = true;
String URL;
String jsonBody;

public WebserviceCall(Context context, String URL, String jsonRequestBody, String dialogMessage, boolean showDialog, AsyncResponse delegate){
    this.context = context;
    this.URL = URL;
    this.jsonBody = jsonRequestBody;
    this.dialogMessage = dialogMessage;
    this.showDialog = showDialog;
    this.delegate = delegate;
}

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

    if(Utils.isNetworkAvailable(context)) {


        if (showDialog) {
            dialog = new ProgressDialog(context);
            dialog.setMessage(dialogMessage);
            dialog.show();
        }
    }

        else {

            Utils.showDialog(context, context.getString(R.string.networkWarning));

        }

}


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

    // creating okhttp client
    OkHttpClient client = new OkHttpClient();

   //   client.setConnectTimeout(10L, TimeUnit.SECONDS);
    // creating request body
    RequestBody body;
    if(jsonBody != null) {
        body = RequestBody.create(URLENCODE, jsonBody);
    }else{
        body = null;
    };

        // creating request
        Request request = new Request.Builder()
                .post(body)
                .url(URL)
                .build();

        // creating webserivce call and get response

        try {
            Response response = client.newCall(request).execute();
            String res = response.body().string();
            Log.d("myapp", res);
            return res;

        } catch (IOException e) {
            e.printStackTrace();
        }


    return null;
}


@Override
protected void onPostExecute(String s) {
    super.onPostExecute(s);
    if(dialog != null && showDialog){
        if(dialog.isShowing()){
            dialog.dismiss();
        }
    }
    if(s != null){

        delegate.onCallback(s);
    }else{
        Log.d("myapp",getClass().getSimpleName()+": response null");
    }
}

}

why is it happening so? can anyone help me with this please?

2 Answers 2

1

You're not running the script on your Android device, are you?

The answer to that is most likely no. Meaning it isn't on localhost (or 127.0.0.1). Find the internal IP (192.168.x.x) of the device that actually has the script and connect to that instead.

The socket timeout is because it can't connect to the Android device because there's nothing there.

Sign up to request clarification or add additional context in comments.

6 Comments

yes I am testin on my device, but I am using the same net provider as the desktop on device using wifi
@Sid so?? Localhost is the device itself. That's why you need the internal IP. The internal IP is the location it has when connected to a given router, and that IP is always 192.168.x.x. If I told you my internal IP was 192.168.1.101, you wouldn't be able to connect to it because we're on a different network. If the devices are connected to different networks you need the external IP (any numbers in the 0-255 range with the exception of localhost and internal IPs). You can't connect to localhost unless the script is on the same device
You should really read this related to how localhost works
how to check ip of device
As i used my device ip now its showing failed to connect,
|
0

If you try connecting via android emulator you must use 10.0.2.2 ip.

Via genymotion - 10.0.3.2.

If you use hardware device with mobile internet you must to know your pc ip in internet, for example use: https://2ip.ru/

If you use wi-fi check ip your pc in your net via "ipconfig" command at console

For connecting with socket you also must to know port that your server used

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.