我尝试使用HttpUrlConnection使我的应用程序与我的php服务器通信。我写了一个在我的电脑上工作正常的课程,但是当我在手机上执行它时根本不起作用。
这是我的代码:
String data = "username=" + URLEncoder.encode(username, "UTF-8") + "&password=" + URLEncoder.encode(password, "UTF-8") + "&remember=1";
connection = (HttpURLConnection) new URL(BASE_URL + "user/login/app").openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", String.valueOf(data.length()));
connection.setDoInput(true);
connection.setDoOutput(true);
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.writeBytes(data);
out.flush();
out.close();
DataOutputStream out = new DataOutputStream(connection.getOutputStream());抛出这个例外:
E/Cloud (10393): java.io.IOException
E/Cloud (10393): at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:85)
E/Cloud (10393): at libcore.net.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:194)
E/Cloud (10393): at com.andryr.runningpal.data.cloud.Cloud.login(Cloud.java:139)
E/Cloud (10393): at com.andryr.runningpal.data.SessionList$2.onLogin(SessionList.java:177)
E/Cloud (10393): at com.andryr.runningpal.ui.dialog.LoginDialogFragment$2.onClick(LoginDialogFragment.java:56)
E/Cloud (10393): at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:169)
E/Cloud (10393): at android.os.Handler.dispatchMessage(Handler.java:99)
E/Cloud (10393): at android.os.Looper.loop(Looper.java:154)
E/Cloud (10393): at android.app.ActivityThread.main(ActivityThread.java:4624)
E/Cloud (10393): at java.lang.reflect.Method.invokeNative(Native Method)
E/Cloud (10393): at java.lang.reflect.Method.invoke(Method.java:511)
E/Cloud (10393): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:809)
E/Cloud (10393): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:576)
E/Cloud (10393): at dalvik.system.NativeStart.main(Native Method)
我在计算机上测试了这段代码,并没有抛出任何异常。 我的清单:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
由于
答案 0 :(得分:6)
您可能正在尝试在UI线程上执行网络操作,Android 3.0+
设备不允许这样做。它们将抛出异常,指示您正在UI线程上执行网络操作。
尝试使用AsyncTask
或单独Thread
执行网络操作。