gpt4 book ai didi

php - Android 没有收到来自 PHP 服务器的响应

转载 作者:搜寻专家 更新时间:2023-11-01 09:50:15 24 4
gpt4 key购买 nike

出于调试目的,我的 PHP 服务器向我的 Android 客户端回显了一个非常简单的字符串:

<?php echo "I REALLY LIKE PIE" ?>

我的 Android 客户端有以下代码来接收这样的字符串:

URL url = new URL("http://192.168.0.107/index.php");
urlConnection = (HttpURLConnection) url.openConnection();


urlConnection.setReadTimeout(10000);
urlConnection.setConnectTimeout(15000);
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.connect();

int HTTPResult = urlConnection.getResponseCode();
if (HTTPResult == HttpURLConnection.HTTP_OK) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String output = "";
while ((output = bufferedReader.readLine()) != null) {
returnedString.append(output);
}
bufferedReader.close();

}

urlConnection.disconnect();

然而,变量“output”为空,因此返回的字符串也为空。为什么我没有收到回复?

最佳答案

  1. 添加用于调试目的的日志或使用带断点的 android 调试器。
  2. 确保您已对 php 配置文件进行必要的更改,以便通过您的手机访问它。它应该工作。如果问题仍然存在,请告诉我。 (我一直在使用这段代码进行一些小的改动,以便之后解析 JSON 对象,但由于在你的情况下它只是一个字符串,所以它应该可以工作。
  3. 为了更好、更简单和优化,使用 OkHttp 或 Volley

    URL url = new URL("http://192.168.0.107/index.php");
    urlConnection = (HttpURLConnection) url.openConnection();
    BufferedReader reader = null;

    urlConnection.setReadTimeout(10000);
    urlConnection.setConnectTimeout(15000);
    urlConnection.setRequestMethod("POST");
    urlConnection.setDoOutput(true);
    urlConnection.setDoInput(true);
    urlConnection.setRequestMethod("GET");
    urlConnection.connect();

    // Read the input stream into a String
    InputStream inputStream = urlConnection.getInputStream();
    StringBuffer buffer = new StringBuffer();
    if (inputStream == null) {

    // Nothing to do.

    }
    reader = new BufferedReader(new InputStreamReader(inputStream));

    String line;
    while ((line = reader.readLine()) != null) {
    // Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
    // But it does make debugging a *lot* easier if you print out the completed
    // buffer for debugging.
    buffer.append(line + "\n");
    }


    bufferedReader.close();

    }

    urlConnection.disconnect();

关于php - Android 没有收到来自 PHP 服务器的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36513103/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com