我不知道为什么当我调用 GetPHPData() 函数时会得到空值。 “out”变量不返回任何内容(“”)。我做了一个 Toast.makeTest 它返回空字符串。请帮忙。这是我的代码:
public class PHPConnect extends Activity
{
String url = "http://122.2.8.226/MITBookstore/sqlconnect.php";
HttpURLConnection urlConnection = null;
String out = null;
public String GetPHPData()
{
try {
urlConnection = (HttpURLConnection) new URL(url).openConnection();
urlConnection.setConnectTimeout(5000);
urlConnection.setReadTimeout(10000);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try
{
BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
out = readStream(in);
}
catch (Exception e)
{
Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
}
finally
{
urlConnection.disconnect();
return out;
}
}
private String readStream(BufferedReader is)
{
try
{
ByteArrayOutputStream bo = new ByteArrayOutputStream();
int i = is.read();
while(i != -1)
{
bo.write(i);
i = is.read();
}
return bo.toString();
} catch (IOException e)
{
return e.getMessage();
}
}
}
顺便说一下,我正在运行一个 wamp 服务器,并且我端口转发了我的路由器,在本地主机上,该 url 有效,但在远程连接上,它不会返回字符串。你可以尝试一下这个url,结果是:“This is the output:emil”
最佳答案
您能否尝试下面一段对我有用的代码,并在 android list 文件中添加 INTERNET 权限。如果仍然无法正常工作,则可能是服务器端出现问题,然后尝试调试它。
URL url;
try {
url = new URL("myurl");
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader isw = new InputStreamReader(in);
int data = isw.read();
while (data != -1) {
char current = (char) data;
data = isw.read();
System.out.print(current);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
关于java - 如何从php读取字符串到android studio(java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30296878/