目前,我有一个登录代码,它会将数据发布到PHP脚本并读取脚本输出的数据(JSON编码)以确定登录凭据是否正确。
以下是我的LoginActivity.java
的一部分,在点击登录按钮时调用:
public void login(View view) {
String usernameValue = username.getText().toString(),
passwordValue = password.getText().toString(),
orgValue = org.getText().toString();
if (orgValue.matches("")) {
snackbar.make(view, "Organisation cannot be blank", Snackbar.LENGTH_LONG).show();
} else if (usernameValue.matches("")) {
snackbar.make(view, "Username cannot be blank", Snackbar.LENGTH_LONG).show();
} else if (passwordValue.matches("")) {
snackbar.make(view, "Password cannot be blank", Snackbar.LENGTH_LONG).show();
} else {
/**
* Login code goes here.
* This is where the error seems to be at.
*/
URL url;
String data;
try {
url = new URL("http://myurl.com/verify/users.php");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setReadTimeout(15000);
connection.setConnectTimeout(15000);
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
data = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(usernameValue, "UTF-8") +
"&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(passwordValue, "UTF-8") +
"&" + URLEncoder.encode("org", "UTF-8") + "=" + URLEncoder.encode(orgValue, "UTF-8");
OutputStream outputStream = connection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
writer.write(data);
writer.flush();
writer.close();
outputStream.close();
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
JsonReader reader = new JsonReader(new InputStreamReader(connection.getInputStream()));
int success = -1;
String message = null;
reader.beginArray();
while (reader.hasNext()) {
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
switch (name) {
case "success":
success = reader.nextInt();
break;
case "error_message":
message = reader.nextString();
break;
default:
reader.skipValue();
break;
}
}
reader.endObject();
}
reader.endArray();
reader.close();
if (success == 1) {
snackbar.make(view, "You are successfully logged in as " + usernameValue + "!", Snackbar.LENGTH_LONG).show();
}
else {
snackbar.make(view, "Error: " + message, Snackbar.LENGTH_LONG).show();
}
}
else {
snackbar.make(view, "Error " + responseCode + " encountered. Please try again later.", Snackbar.LENGTH_LONG).show();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
然而,当我点击登录按钮时,应用程序在logcat中崩溃并显示以下消息:
04-24 16:55:24.251 16674-16674/com.example.android.loginexample E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.loginexample, PID: 16674
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:5242)
at android.widget.TextView.performClick(TextView.java:10530)
at android.view.View$PerformClick.run(View.java:21185)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6872)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5242)
at android.widget.TextView.performClick(TextView.java:10530)
at android.view.View$PerformClick.run(View.java:21185)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6872)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
at java.net.InetAddress.getAllByName(InetAddress.java:215)
at com.android.okhttp.HostResolver$1.getAllByName(HostResolver.java:29)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:232)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:124)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:370)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:298)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:399)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:110)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:221)
at com.example.android.loginexample.LoginActivity.login(LoginActivity.java:68)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5242)
at android.widget.TextView.performClick(TextView.java:10530)
at android.view.View$PerformClick.run(View.java:21185)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6872)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
任何帮助将不胜感激!在此先感谢:)
答案 0 :(得分:0)
如果我是你,我不会尝试在主线程中发出URL请求,我建议你使用AsyncTask。
但是,如果您真的想在主线程中执行此操作,可以在活动的onCreate中写下:
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
答案 1 :(得分:0)
android.os.NetworkOnMainThreadException
以上一行说明了一切。在android中你不能在主线程中执行网络操作。你在这里执行http请求。而不是这样做使用AsyncTask或不同的线程。