如何在Android上发出与此PHP代码相同的请求?

I am new to both PHP and Android.

I am doing this request like this in PHP which works well. The "name" will contain a variable like "upperLight" so that we can compare with the android code.

$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

socket_connect($sock,"192.168.2.104", 80);

$msg = 'a';
if (isset($_POST["name"])){
    $msg= $_POST["name"] ;
}

socket_write($sock, $msg);

I am trying to do the same in android like this but its not working.

        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        pairs.add(new BasicNameValuePair("upperLight","1"));

        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(URLTest);
        post.setEntity(new UrlEncodedFormEntity(pairs));
        HttpResponse execute = client.execute(post);

On the other end (192.168.2.104) i am checking for the word "upperLight" in the request.

EDIT : the variable URLTest contains - "192.168.2.104:80"

  • try this

    URL url = new URL("http://192.168.2.104:80");
    URLConnection con = url.openConnection();
    con.setDoOutput(true);
    OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());
    out.write( "upperLight" );
    out.flush();
    

The PHP code is connecting to a TCP socket on port 80, while the Android code is connecting to an HTTP server.

Those are two completely different things. If you need to port the PHP code to Java/Android, you would start by using the corresponding library, which is Socket.