【发布时间】:2017-11-08 20:19:51
【问题描述】:
我需要从我的 Web 服务中获取登录详细信息,以在我的应用中验证登录。下面是完成这项工作的代码。
try {
//Apache Libraries and namevaluepair has been deprecated since APK 21(?). Using HttpURLConnection instead.
URL url = new URL(wsURL + authenticate);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
OutputStream os = connection.getOutputStream();
os.write(postParam.getBytes());
os.flush();
os.close();
// Fetching the response code for debugging purposes.
int responseCode = connection.getResponseCode();
Log.d(TAG, "POST Response Code: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
//Adding every responseCode in the inputLine.
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
Log.d(TAG, "HTTP Response: " + response.toString());
//TODO: Check login logic again
//Sets Authentication flag
if (!response.toString().contains("Authentication Failed!")) {
authFlag = true;
Log.i(TAG, "Authentication Completed: Logged in Successfully!");
try {
JSONObject jsonObject = new JSONObject(response.toString());
JSONArray jsonArray = jsonObject.getJSONArray("rows");
JSONObject beanObject = jsonArray.getJSONObject(0);
userBean = new UserBean(username, beanObject.getString("User_FullName"), beanObject.getInt("UserType_Code"));
} catch (Exception e) {
e.printStackTrace();
}
}
} else {
Log.e(TAG, "Error!!! Abort!!!");
}
connection.disconnect();
} catch (MalformedURLException e) {
System.out.println("URLConnection Exception: " + e);
} catch (IOException e) {
System.out.println("IOStream Exception: " + e);
}
return postParam;
}
我面临的问题是我在我的 logcat 中看不到任何与之相关的内容,但在调试时我发现控件转到 } catch (MalformedURLException e) {
但是 System.out.println("URLConnection Exception: " + e);
永远不会被执行。
我是 Android 开发的新手,所以可能有些东西我看不到。请帮忙。
编辑 - 我第一次尝试使用Log.e,但它不起作用,所以我输入了System.out.println,它也不起作用。
【问题讨论】:
-
用于调试放置异常并查看调试点是否进入 catch 块内
-
使用
Log.e而不是System.out.println -
它确实进入了 catch 块,但打印语句从未执行我尝试使用 Log.e 但没有运气
-
@AshvinSharma 如果它没有记录,你怎么知道它进入了 catch 块?确保您的 android studio 设置为收集正确的日志(无过滤)。否则,通过调用
throw new IOException("");或其他方式确保它确实出错 -
我在调试器中看到了它去捕获块,如果你愿意,我可以发布一张图片。我没有得到最后一部分,投掷会有帮助吗?。