我正在尝试进行 JSON AsynTack 服务调用以登录我的用户。不幸的是,它在 openConnection 上崩溃并显示错误消息:执行 doInBackground() 时发生错误。我是一名 iOS 开发人员,正在尝试学习 Android,所以如果我遗漏了一些简单的东西,我深表歉意。
public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
private final String mEmail;
private final String mPassword;
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
UserLoginTask(String email, String password) {
mEmail = email;
mPassword = password;
}
@Override
protected Boolean doInBackground(Void... params) {
ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if(info==null || !info.isConnected()) {
return false;
}
try {
URL url = new URL("http://urlForLoginHere");
urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000);
urlConnection.setConnectTimeout(15000);
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("username", mEmail)
.appendQueryParameter("password", mPassword);
String query = builder.build().getEncodedQuery();
OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return false;
}
// reader = new BufferedReader(new InputStreamReader(inputStream));
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return false;
}
String jsonString = buffer.toString();
urlConnection.setConnectTimeout(3000);
urlConnection.connect();
if (urlConnection.getResponseCode() == 200) {
// try {
//
// }
return true;
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}