错误:java.net.ConnectException:无法连接到/10.0.2.2(端口8000):连接失败:

时间:2016-12-10 23:05:52

标签: java php android mysql

我正在尝试通过Android Studio IDE连接到Android模拟器。我在Mac上使用命令php -S localhost:8000运行PHP服务器(因为这在使用XCODE IDE的IoS中工作)。我有一个Async任务,我想运行以通过addtoDB方法将数据写入SQL服务器。几篇帖子建议使用10.0.2.2。我用它。但是我仍然得到同样的错误。以下是我的代码。这很简单,但不起作用。此外,我无法ping 10.0.2.2。我尝试了localhost,并给出了相同的错误。有一次,它确实工作说它连接到PHP服务器,但它总是在PHP窗口上给出(意外的文件结束)。 PHP代码显示在Java代码之后。

我想说IoS上每次都有效,我已经成功移植了iphone并使用它。我在这里做错了什么。

提前感谢您的帮助。

拉​​梅什

class doHTTPPost extends AsyncTask<Void,Void,String> {

/*
private String Url;
private Integer tos;

public  doHTTTPPost(String url, Integer typeOfService) {
    Url = url;
    tos = typeOfService;
}
*/
protected String doInBackground(Void... params) {
    //now call your ipify method which is doing the networking or calling a method that might be doing the networkign

    //getContents("http://localhost:8080");
    String result ="";

    result = addToDb();

    return result;
}

private String addToDb() {



    String urlParameters  = "Fname=Ram&Lname=Ramesh&Msisdn=6785459898";
    byte[] postData       = urlParameters.getBytes( StandardCharsets.UTF_8 );
    int    postDataLength = postData.length;
    //String request        = "http://example.com/index.php";
    //let myUrl = URL(string: "http://localhost:8000/serviceadd-all-good.php/")
    String request = "http://10.0.2.2:8000/serviceaddAndroid.php/";

    URL url=null;

    try {
         url = new URL(request);
        HttpURLConnection conn= (HttpURLConnection) url.openConnection();
        conn.setDoOutput( true );
        conn.setInstanceFollowRedirects( false );
        conn.setRequestMethod( "POST" );
        conn.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty( "charset", "utf-8");
        conn.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
        conn.setUseCaches( false );
        DataOutputStream wr = new DataOutputStream( conn.getOutputStream());
            wr.write( postData );
        } catch (IOException e) {

        System.out.println("Err :"+e);

        Log.i("Add","Error");
        return("Error");
    }

    Log.i("Add","Done");

    return("Done");
}

PHP代码是

<?php
$dir = 'sqlite:/Users/lakshmi/Documents/ServiceTesting.sqlite';
$dbh  = new PDO($dir) or die("cannot open the database");
// Read request parameters
$fname = $_REQUEST["Fname"];
$lname = $_REQUEST["Lname"];
$msisdn = $_REQUEST["Msisdn"];

//$dbh->exec(  "INSERT INTO Service_Testing (ID, Status, Tech) VALUES ('$id','$status','$tech')");

$dbh->exec( "INSERT INTO TestWithAndroid (Fname, Lname, Msisdn ) VALUES ('$fname','$lname','$msisdn')");

//$dbh->exec("INSERT INTO Result (Serial, Testid, Result) VALUES ('$serial','$testid','$result')");
//echo "Row inserted \n";
//$dbh->exec('INSERT INTO Result (Serial, Testid, Result) VALUES (5,"st3","Fail")');
//echo "Row inserted \n";

// Send data back
//echo json_encode($returnValue);

?>

0 个答案:

没有答案