Java 使用localhost android获取套接字连接超时

Java 使用localhost android获取套接字连接超时,java,php,android,sockets,serversocket,Java,Php,Android,Sockets,Serversocket,我已经用php在本地主机上创建了一个api。正如我在《邮递员》中测试的那样,它工作得很好,但当我从android调用url时,它给出了一个套接字连接超时的异常 其AMPS服务器无法连接 这是我的php脚本: <?php //echo error error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE); ini_set('display_errors', '1'); // require database require

我已经用php在本地主机上创建了一个api。正如我在《邮递员》中测试的那样,它工作得很好,但当我从android调用url时,它给出了一个套接字连接超时的异常

其AMPS服务器无法连接

这是我的php脚本:

    <?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();
}

数据库

    <?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;
    }
}

?>

安卓

    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");
    }
}
String-token=tokenPreference.getString(“token”,“”);
如果(!token.equals(“”){
//字符串cno=preferences.getString(“cono”,null);
字符串[]键=新字符串[]{“移动设备编号”、“设备id”};
字符串[]值=新字符串[]{preferences.getString(Const.DRIVER_MOBILE_NUMBER,“”),标记};
最终字符串jsonRequest=SecondUtils.createJsonRequest(键、值);
字符串URL=”http://192.168.44.1/fuelOneTest/insertDevice.php";
新的WebserviceCall(MainDriver.this,URL,jsonRequest,“加载”,true,新的AsyncResponse(){
@凌驾
公共void onCallback(字符串响应){
Log.d(“myapp”,响应);
//Toast.makeText(RegisterDriver.this,model.getResponse_desc(),Toast.LENGTH_SHORT.show();
试一试{
JSONObject JSONObject=新JSONObject(响应);
//将以下条件更改为0..对于测试,将其更改为1
if(jsonObject.get(“message”).equals(“Success”)){
Log.d(“DeviceToken”,“插入设备令牌”);
}否则{
}
}捕获(JSONException je)
{
je.printStackTrace();
}
}
}).execute();
}
公共类WebserviceCall扩展异步任务{
//响应接口
异步响应委托;
private final MediaType URLENCODE=MediaType.parse(“application/json;charset=utf-8”);
进程对话;
语境;
字符串对话框消息;
布尔showDialog=true;
字符串URL;
字符串jsonBody;
公共WebserviceCall(上下文上下文、字符串URL、字符串jsonRequestBody、字符串dialogMessage、布尔showDialog、异步响应委托){
this.context=上下文;
this.URL=URL;
this.jsonBody=jsonRequestBody;
this.dialogMessage=dialogMessage;
this.showDialog=showDialog;
this.delegate=委托;
}
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
if(Utils.isNetworkAvailable(上下文)){
如果(显示对话框){
dialog=新建进度对话框(上下文);
设置消息(dialogMessage);
dialog.show();
}
}
否则{
Utils.showDialog(context,context.getString(R.string.networkWarning));
}
}
@凌驾
受保护字符串doInBackground(无效…参数){
//创建okhttp客户端
OkHttpClient=新的OkHttpClient();
//设置连接超时(10L,时间单位为秒);
//创建请求主体
请求主体;
if(jsonBody!=null){
body=RequestBody.create(URLENCODE,jsonBody);
}否则{
body=null;
};
//创建请求
Request Request=newrequest.Builder()
.职位(机构)
.url(url)
.build();
//创建webserivce调用并获取响应
试一试{
Response=client.newCall(request.execute();
String res=response.body().String();
Log.d(“myapp”,res);
返回res;
}捕获(IOE异常){
e、 printStackTrace();
}
返回null;
}
@凌驾
受保护的void onPostExecute(字符串s){
super.onPostExecute(s);
if(dialog!=null&&showDialog){
if(dialog.isShowing()){
dialog.dismise();
}
}
如果(s!=null){
一次收回委托书;
}否则{
Log.d(“myapp”,getClass().getSimpleName()+”:response null);
}
}
}


为什么会这样?有人能帮我吗?

你没有在Android设备上运行脚本,是吗

答案很可能是否定的。这意味着它不在
localhost
(或
127.0.0.1
)上。查找实际具有脚本的设备的内部IP(
192.168.x.x
),然后连接到该设备


套接字超时是因为它无法连接到Android设备,因为那里什么都没有

如果您尝试通过android emulator连接,则必须使用10.0.2.2 ip

通过genymotion-10.0.3.2

如果您将硬件设备与移动互联网一起使用,您必须了解互联网中的pc ip,例如使用:

如果您使用wi-fi,请通过控制台上的“ipconfig”命令在网络中检查您的电脑的ip地址


要连接socket,您还必须知道服务器使用的端口

是的,我正在我的设备上测试,但我使用的网络提供程序与桌面设备上使用的网络提供程序相同wifi@Sid所以Localhost是设备本身。这就是为什么您需要内部IP。内部IP是连接到给定路由器时的位置,并且该IP始终
192.168.x.x
。如果我告诉你我的内部IP是192.168.1.101,你将无法连接到它,因为我们在不同的网络上。如果设备连接到不同的网络,则需要外部IP(0-255范围内的任何数字,本地主机和内部IP除外)。除非脚本位于同一设备上,否则无法连接到localhost。您应该真正了解localhost如何工作如何检查设备的ip当我使用设备ip时,其显示无法连接,
    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");
    }
}