I have the following code in an Android application:
public static HttpResponse dbPost(String handlerUrl, List<NameValuePair> postData) {
HttpClient httpclient = new DefaultHttpClient();
String postUrl = constants.postUrl();
HttpPost httppost = new HttpPost(postUrl);
HttpResponse response = null;
System.out.print("Catch 0");
try {
httppost.setEntity(new UrlEncodedFormEntity(postData));
response = httpclient.execute(httppost);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.print("Catch 1");
return response;
}
I have a button that calls this block. If I press the button, the console will print “Catch 0” (but NOT “Catch 1”). If I press the button again (same instance), the console will print “Catch1Catch0”. What’s the problem?
I’m a bit new to Java so bear with me.
You need to call flush since you’re using
print.The default behavior of
PrintStreamis to only flush when a newline is written. (This behavior is documented in write(int).)If you used
printLninstead ofprint, the stream would flush automatically. Without that, you need to explicitly flush the output stream.