无法发送简单的 GET Http 请求

Not able to send simple GET Http request

我在清单中包含了以下权限:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

我正在使用此代码:

try {
      java.net.URL url = new URL("http://www.temp372.000webhostapp.com/s.php?t=hello_there");
      HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
      e.printStackTrace();
      t1.setText("problem occured..");
}

以下是 PHP 代码:

<?php
$fn = "android.txt";
$data = "";
// get whatever they send and store it to the file.
if($_GET["t"])
{
    $data = $_GET["t"];
    if ($data !== '')
    {
        $myfile = fopen($fn, "a");
        fwrite($myfile, $data . "\n");
        fclose($myfile);
    }
}
?>

没有出现错误,我正在尝试 运行 此应用程序进入 bluestacks 和我的手机 (ROG Phone)。 但结果是一样的,没有错误或任何因为 textview 没有设置,只是我的 PHP 代码没有收到信息但是当我在我的网络浏览器中尝试相同的 URL 时,PHP 代码运行很酷。

HTTP 或 "clear text" 默认禁止,您应该在 AndroidManifest.xml android:usesCleartextTraffic="true"

效果很好,以下是我得到的东西: 我不必将以下内容添加到清单中:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

我也不必在清单中添加任何权限,例如 android:usesCleartextTraffic="true" 或任何 network_security_config.xml。

当我 运行 代码进入后台线程中的 AsyncTask 时它起作用了,如下所示:

AsyncTask.execute(new Runnable() {
            @Override
            public void run() {
                HttpClient httpclient = new DefaultHttpClient();
                try {
                    httpclient.execute(new HttpGet("https://temp372.000webhostapp.com/s_get.php?t=MyWorld"));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

为此我感谢 Artem 以及其他所有竭尽全力的人。