无法发送简单的 GET Http 请求



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

<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(中。 但是结果是相同的,没有错误或任何内容,因为文本视图没有设置,只是我的PHP代码没有接收信息,但是当我尝试相同的URL进入我的Web浏览器时,PHP代码运行很酷。

默认情况下禁止HTTP或"明文",您应该在AndroidManifest<应用程序>中允许它.xmlandroid: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();
}
}
});

我为此感谢阿尔乔姆和其他所有尽力而为的人。

最新更新