我有问题!我连接了一个 php 页面以连接数据库,该方法在 Froyo 上运行良好,但在较新版本的 Android 上不起作用。有什么问题?
public static String interact(String request){
String result="test";
String site = "http://xxxx.net:nnn/xxx";
URL url = new URL(site);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.connect();
OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());
wr.write(request);
wr.flush();
wr.close();
Scanner in = new Scanner(connection.getInputStream());
while(in.hasNextLine())
result+=in.nextLine();
connection.disconnect();
return result;
}
catch (UnknownHostException e) {
return e.getMessage();
} catch (IOException ex) {
return ex.getMessage();
}
catch (Exception ex){
return ex.getMessage();
}
}
我需要发送数据并获得响应,但在比 2.2 更高的 Android 上它只会给我 null。
最佳答案
您正在主线程上运行网络请求
。
Android >=3.0 不允许这样做。你需要使用 AsyncTask调用网络请求
关于Android 与 php 交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13591294/