首页 > 解决方案 > 无法使用 Java 代码从我的 Android Studio 项目中的 000webhost 获取文本数据

问题描述

我是 Android Studio 开发的新手,但是我在 Unity3D C# 开发方面经验丰富。我有一个返回一些文本数据的 PHP 脚本,它托管在 000webhost 上。我可以使用 Unity3D C# 脚本使用UnityWebRequest类及其downloadHandler.text.

现在我正在 Android Studio Java 中尝试。问题是我无法从 PHP 脚本中获取数据。我用不同的 URL 尝试了相同的代码,它可以工作。我尝试将 URL 更改为“www.bing.com”,它会显示该 Bing 网页的数据。它只能从 000webhost 获取数据。请告诉我 Android Studio (Java) 和 000webhost 有什么问题。

这是我的代码:

@Override protected Void doInBackground(Void... voids)
{
    try
    {
        URL url = new URL("https://000webhost_URL"); // www.bing.com works
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        InputStream inputStream = httpURLConnection.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));

        String line = "";
        while (line != null) {
            line = br.readLine();
            data = data + line;

        }
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
    return null;
}

@Override protected void onPostExecute(Void aVoid)
{
    super.onPostExecute(aVoid);
    Log.d(tag, "Fetched data: " + data);
}

/*
I get empty Data when it is fetched from 000webhost
Fetched data: 

When I try from bing.com I get the response stream:
Fetched Data: <!DOCTYPE html><html lang="en"><head><meta content="text/html; /....
*/

标签: javac#android-studiounity3dweb-hosting

解决方案


推荐阅读