Issues comparing the result of an HttResponse in android
I'm having an issue trying to compare the result of an HttpResponse with an simple string.
What the code below do, is just get the response of an Http request. In this case the result of the request is a simple "ok", but when I try to compare it with another string the conditional doesn't work.
I'm able to show the response via toast message...to debug it and to confirm that it is what I'm expecting, but I don't know why the conditional is not working.
Thank's in advance.
imports go here...
public class HttpTest extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { "http://www.ecoeficiencia-ambiental.com/test/" });
}
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine开发者_开发知识库()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
protected void onPostExecute(String result) {
if(result == "ok"){
Toast.makeText(HttpTest.this, result, Toast.LENGTH_LONG).show();
}else{
Toast.makeText(HttpTest.this, "the conditional fails, the result is: "+result, Toast.LENGTH_LONG).show();
}
}
}
}
Note: the manifest has the permission to use internet. both the code and the URL are functional.
You should not use the equality operator to compare strings like that
Try
result.equals("ok");
Oh, interesting! I guess that the string you get from reponse Entity including these things as well:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
Not just a single string 'ok' as you think. That's why comparison fails.
You can confirm reponse by:
string response = EntityUtils.toString(execute.getEntity());
Have fun :)
精彩评论