出于调试目的,我的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"为null,因此返回的字符串也是null。为什么我没有得到回应?
- 添加用于调试目的的日志,或者使用带有断点的android调试器
- 确保您已经在php配置文件中进行了必要的更改,以便通过手机访问它。它应该起作用。如果问题仍然存在,请告诉我。(我一直在使用这段代码,后来对JSON对象进行了一些小的修改,但由于它在您的情况下只是一个字符串,所以它应该可以工作
-
为了更好、更容易和优化,使用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();