if-else语句输出总是在httpurlconnection中

时间:2017-11-25 07:51:07

标签: android

我有一个代码可以从服务器返回成功,就像这样:

BufferedReader reader = new BufferedReader(new InputStreamReader(
        is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
    sb.append(line + "\n");
}
is.close();
String response = sb.toString();
//HERE YOU HAVE THE VALUE FROM THE SERVER
Log.d("Your Data", response);

//if(response == "0"){ still not fix
if(response.equals("0")){
    Log.d("berhasil","keknya");
    db.updateContact(new Contact(idsql,null,1,null));
}
else{
    Log.d("Error", "ubah data");
}

在我的logcat中,log.d("your data", response)的输出为0,但语句总是抛出到其他地方,如下所示:

logcat

我该如何解决?

2 个答案:

答案 0 :(得分:0)

您使用以下逻辑逐行构建StringBuilder响应:

sb.append(line + "\n");

因此,如果您只有一个0的响应,那么您的字符串构建器实际上会包含这个:

0\n

如果这个猜想是正确的,那么如果你修剪空格然后比较为零,你应该得到你期望的结果:

if (response.trim().equals("0")) {
    Log.d("berhasil", "keknya");
    db.updateContact(new Contact(idsql, null, 1, null));
}
else {
    Log.d("Error", "ubah data");
}

请注意,如果您只想检查服务器响应代码,那么HttpURLConnection API已经公开了一种方法:

try {
    URL url = new URL("http://www.someurl.com");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    int responseCode = conn.getResponseCode();

    if (responseCode == HttpURLConnection.HTTP_OK) {
        server_response = readStream(conn.getInputStream());
        Log.v("index", server_response);
    }
} catch (Exception e) {
    // do something
}

答案 1 :(得分:0)

响应中可能有一些空格,因此if不会执行, 尝试将条件更改为:

if(response.trim().equals("0"))

trim将删除所有的初始和最终空格,并为您提供仅在结尾或开头没有空格的纯String

相关问题