我不知道为什么我得到一个空值,当我调用GetPHPData()函数。"out"变量不返回任何东西(")。我敬酒。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: email "
你能试试下面的代码是为我工作的,也在android manifest文件中添加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();
}