Statement in Catch isn't executed [duplicate] - java

This question already has answers here:
How to print to the console in Android Studio?
(8 answers)
Closed 5 years ago.
I need to fetch login details from my web service to authenticate login in my app. Below is the code which does the job.
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;
}
Issue I'm facing is I don't see anything related to it in my logcat but on debugging I find that the control goes to
} catch (MalformedURLException e) {
but System.out.println("URLConnection Exception: " + e); is never executed. I'm novice at Android dev so there might be something which I can't see. Please help.
EDIT - I first tried with Log.e but it didn't work so I put System.out.println which didn't work either.

You should not use System.out,
instead use logging functions like logcat for debugging.
In this example, considering that the catch catches an error, you should use:
private static final String TAG = "MyActivity";
...
catch (MalformedURLException e) {
Log.e(TAG, "URLConnection Exception: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IO error: " + e.getMessage());
}
Here is an explanation of how to use them properly.
If you can't see logcat, go there.

just try
Log.e("tag","Exception: " + e);
and you can find it in android monitor

Related

Code skips to finally after HTTPURLConnection connect

I'm trying to learn Android development by creating the movies app from the Google Udacity course. In my code below upon executing urlConnection.connect(), the code automatically goes to the finally block without any errors/exceptions.
Can you please help me see what's wrong with my code? Thanks!
public class FetchMoviesTask extends AsyncTask<Void, Void, String> {
private final String LOG_TAG = FetchMoviesTask.class.getSimpleName();
protected String doInBackground(Void... params) {
String JSONResponse = null;
//These are declared outside as they'll be used in both try and finally blocks
BufferedReader reader = null;
HttpURLConnection urlConnection = null;
try {
//construct your URL from a URI
Uri.Builder URIbuilder = new Uri.Builder();
URIbuilder.scheme("http")
.authority("api.themoviedb.org")
.appendPath("3")
.appendPath("movie")
.appendPath("popular")
.appendQueryParameter("api_key", BuildConfig.TMDB_API_KEY);
//instantiate URL
URL popularURL = new URL(URIbuilder.toString());
Log.v(LOG_TAG, "Built URL: " + popularURL.toString());
//create and open HTTP connection
urlConnection = (HttpURLConnection) popularURL.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
//InputStream is needed to read the response
//http://developer.android.com/reference/java/net/HttpURLConnection.html
InputStream inputStream = urlConnection.getInputStream();
if (inputStream == null) {
Log.e(LOG_TAG, "Null input stream");
return null; //no data returned from HTTP request
}
//!!want to see what InputStream looks like
Log.v(LOG_TAG, "inputStream.toString(): " + inputStream.toString());
//BufferedReader is used to wrap a Reader and buffer its input
//to read InputStream, a "reader" is required and that's InputStreamReader (duh)
//http://developer.android.com/reference/java/io/BufferedReader.html
reader = new BufferedReader(new InputStreamReader(inputStream));
//!!want to see what BufferedReader looks like
Log.v(LOG_TAG, "reader.toString(): " + reader.toString());
//replaced StringBuffer w/ StringBuilder. will it work?
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
builder.append(line + "\n");
}
if (builder.length() == 0) return null; //empty stream. no point in parsing
JSONResponse = builder.toString();
Log.v(LOG_TAG, "JSON Response: " + JSONResponse);
return parseJSON(JSONResponse);
} catch (IOException e) {
Log.e(LOG_TAG, "Error", e);
return null;
} catch (JSONException e) {
Log.e(LOG_TAG, "Error parsing JSON", e);
return null;
} catch (Error e) {
Log.e(LOG_TAG, "Unknown error", e);
} finally {
if (urlConnection != null) urlConnection.disconnect();
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
//will only be triggered if there's an error getting/parsing data
return null;
}
}
CommonsWare pointed me to the possible cause of the issue, which was a missing INTERNET permission. Adding it solved my problem. Thanks for all the responses!
The problem is this comment in your code:
//will only be triggered if there's an error getting/parsing data
That's false.
The return in the try block won't be ignored if a finally block is defined, only if that finally block also includes a return.
In other words, if you have "return" in both try and finally, the one inside finally is the one which gets executed.
Source: Java try-finally return design question
Edit:
You may want to check this out: Does finally always execute in Java?

HttpUrlConnection sometimes gives EOF exception

I am using HttpUrlConnection and using POST method to get some data from web server. Sometimes, I get the response and at times I get EOFexception
These are the solutions are I have already tried :
1) System.setProperty("http.keepAlive", "false");
2) if (Build.VERSION.SDK != null && Build.VERSION.SDK_INT > 13) {
connection.setRequestProperty("Connection", "close");
}
Below is my code from AsyncTask class;
CODE :
#Override
protected JSONObject doInBackground(KeyValuePair... keyValuePairs) {
JSONObject jsonResponse = new JSONObject();
HttpURLConnection connection = null;
// check if is Internet is available before making a network call
if (isInternetAvailable()) {
try {
jsonResponse = new JSONObject();
URL url = new URL(urlStr);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setUseCaches(false);
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "UTF-8");
if (Build.VERSION.SDK != null && Build.VERSION.SDK_INT > 13) {
connection.setRequestProperty("Connection", "close");
}
// setting post params
StringBuilder builder = new StringBuilder();
for (int i = 0; i < keyValuePairs.length; i++) {
builder.append(URLEncoder.encode(keyValuePairs[i].getKey(), "UTF-8") + "=" + URLEncoder.encode(keyValuePairs[i].getValue(), "UTF-8") + "&");
GeneralUtils.print("key : " + keyValuePairs[i].getKey() + ", value : " + keyValuePairs[i].getValue());
}
String postData = builder.toString();
postData = postData.substring(0, postData.length() - 1);
GeneralUtils.print("postData " + postData);
byte[] postDataByteArr = postData.getBytes();
connection.setFixedLengthStreamingMode(postDataByteArr.length);
connection.setConnectTimeout(20000);
DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream());
dataOutputStream.writeBytes(postData);
dataOutputStream.flush();
dataOutputStream.close();
GeneralUtils.print("respCode " + connection.getResponseCode());
// if connection was not successful
if (connection.getResponseCode() != 200) {
jsonResponse.put("status", "Failure");
jsonResponse.put("message", "Something went wrong. Please Try Again");
} else {
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line);
}
reader.close();
String response = sb.toString();
GeneralUtils.print("NetworkCall Server response " + response);
jsonResponse = new JSONObject(response);
}
} catch (JSONException e) {
GeneralUtils.print("NetworkCall.JSONEx 162 " + e);
} catch (MalformedURLException e) {
GeneralUtils.print("NetworkCall.MalformedURLEx " + e);
} catch (IOException e) {
try {
jsonResponse.put("status", "No Internet Connection");
jsonResponse.put("message", "Please check your Internet connection and try again");
} catch (JSONException e1) {
GeneralUtils.print("NetworkCall.JSONEx " + e);
}
} finally {
connection.disconnect();
}
} else {
// if Internet is not available
try {
jsonResponse.put("status", "No Internet Connection");
jsonResponse.put("message", "Please check your Internet connection and try again");
} catch (JSONException e) {
e.printStackTrace();
}
}
return jsonResponse;
}
Many many thanks in advance!
As of now I am following a workaround posted here
which essentially dictates trying to connect N number of times to bypass the EOF exception issue.
In my case, when I catch EOFException, I call the doInBackground again depending upon the reconnectCount;
CODE :
catch (IOException e) {
try {
if (reConnectCount <= 10) {
reConnectCount++;
jsonResponse = doInBackground(keyValuePairs);
} else {
jsonResponse.put("status", "No Internet Connection");
jsonResponse.put("message", "Please check your Internet connection and try again");
}
} catch (JSONException e1) {
GeneralUtils.print("NetworkCall.JSONEx " + e);
}
}
Where jsonResponse essentially holds server response in JSON form. So, whenever doInBackground is successfully executed (i.e. does not get Caught and returns jsonResponse), we overwrite the calling doInBackground's jsonResponse object.

HttpUrlConnection Reading an Input Stream Returns "-1"

I am sending a post request to a server. After a successful request, the response sends pdf data to the client for download. I am trying to generate the pdf file with the response and save it to the Android device. I have successfully created the request, the empty pdf file, and I have even received a successful response. Although, when I call .getInputStream() it returns a "-1". As a result, the while loop exits with the error java.lang.ArrayIndexOutOfBoundsException: length=4096; regionStart=0; regionLength=-1.
I understand why I am receiving this error, but I do not know how to get the data response.
protected Boolean doInBackground(String... params) {
Log.d("LOGOUT", "CREATING REQUEST");
boolean successful = false;
HttpURLConnection connection = null;
URL downloadURL = null;
InputStream inputStream = null;
PrintWriter out= null;
FileOutputStream fileOutputStream = null;
File file = null;
int totalsize;
try {
downloadURL = new URL("http://exampleurl.com");
connection = (HttpURLConnection) downloadURL.openConnection();
connection.setDoOutput(true);
String data = "param=" + URLEncoder.encode(params[0], "UTF-8") + "&submit=" + URLEncoder.encode("Submit", "UTF-8");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", "" + data.length());
String sdCard = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
file = new File(sdCard + File.separator + "test.pdf");
fileOutputStream = new FileOutputStream(file);
out = new PrintWriter(connection.getOutputStream());
out.write(data);
out.close();
inputStream = connection.getInputStream();
int read;
byte[] buffer = new byte[1024];
while ((read = inputStream.read(buffer)) != -1) ; {
Log.d("LOGOUT", "BUFFER: " + read);
// **The LOGOUT message reads "BUFFER: -1" within Logcat**
fileOutputStream.write(buffer, 0, read);
}
successful = true;
} catch (MalformedURLException e) {
Log.d("LOGOUT", "ERROR: " + e);
} catch (UnsupportedEncodingException e) {
Log.d("LOGOUT", "ERROR: " + e);
} catch (FileNotFoundException e) {
Log.d("LOGOUT", "ERROR: " + e);
} catch (IOException e) {
Log.d("LOGOUT", "ERROR: " + e);
} finally {
if (inputStream != null) {
try {
Log.d("LOGOUT", "CLOSING INPUTSTREAM");
inputStream.close();
} catch (IOException e) {
Log.d("LOGOUT", "ERROR: " + e);
}
if (fileOutputStream != null) {
try {
fileOutputStream.close();
Log.d("LOGOUT", "CLOSING FILEOUTPUTSTREAM");
} catch (IOException e) {
Log.d("LOGOUT", "ERROR: " + e);
}
}
}
if (connection != null) {
Log.d("LOGOUT", "CLOSING CONNECTION");
connection.disconnect();
}
}
return successful;
}
I am receiving the correct response headers. I have listed them below...
Connection:Keep-Alive
Content-Disposition:attachment; filename=examplefilename.pdf
Content-Type:application/pdf
Date:Wed, 21 Oct 2015 13:59:45 GMT
Keep-Alive:timeout=5, max=100
Server:Apache/2.2.22
Transfer-Encoding:chunked
Vary:User-Agent
X-Powered-By:PHP/5.3.29
I know for a fact I am sending/receiving a successful request/response, but I am unable to download the pdf data. Finally, I do not have control over the server. I am interacting with a third party application.
What am I doing wrong to accomplish the task? If not that, does anyone have any idea on where I could look to solve the problem? Any guidance is appreciated.

How to get the response data from cloud to string

I want to get the response to a string variable from the data from the cloud.
ClientResource cr = new ClientResource("http://localhost:8888/users");
cr.setRequestEntityBuffering(true);
try {
try {
cr.get(MediaType.APPLICATION_JSON).write(System.out);
} catch (IOException e) {
e.printStackTrace();
}
} catch (ResourceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I have response as JSON in the console and I want to convert it to string , Is the GSON library would be helpful? I haven't used it yet .What modifications should I need to do in my codes? Can anybody help me here.
In fact, Restlet receives the response payload as String and you can directly have access to this, as described below:
ClientResource cr = new ClientResource("http://localhost:8888/users");
cr.setRequestEntityBuffering(true);
Representation representation = cr.get(MediaType.APPLICATION_JSON);
String jsonContentAsString = representation.getText();
Hope it helps you,
Thierry
Below is a working example:
try {
URL url = new URL("http://localhost:8888/users");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Raw Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

Java .getInputStream() openConnection() HTTP response code ERRORS

I am trying to do the following (in Java):
connect to some proxy server & http_url some
But I am having some errors like :
java.net.ConnectException: Connection timed out: connect...
Or errors related to HTTP response code : 302, 400, FileNotFound, file server error, etc.
In some changes I did, I even got 200 code.
(when I only use openConnection() =>( without the proxy IP address).
That is my best run trace.
I have had all class of : (Unknown Source) in the error msg, from IDE Eclipse Luna console.
Some of the error come in the form / or from : .getInputStream() method, I don't know if there is about setDoInput(), setDoOutput, the Encoding, or whatever:
Can some body help me?
Here is my code:
url = new URL(http_url);
HttpURLConnection conn;
try {
conn = (HttpURLConnection)url.openConnection(proxy);
conn.setRequestMethod("GET");
conn.setRequestProperty("User-Agent", USERAGENT);
conn.setUseCaches(false);
conn.setRequestProperty("Accept", "*/*");
conn.addRequestProperty("Referer", "http://www.google.com/");
conn.setRequestProperty("Accept-Encoding", "gzip,deflate,sdch");
conn.setRequestProperty("Accept-Language", "en-US,en;q=0.8");
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
conn.setRequestProperty("X-Requested-With", "XMLHttpRequest");
conn.setDoInput(true);
System.out.println("response msg " + conn.getResponseMessage() + " CODE");
System.out.println("errorStream msg " + conn.getErrorStream());
System.out.println("inputStream msg " + conn.getInputStream());
String header_date = conn.getHeaderField("Date");
System.out.println(" date es: " + header_date);
String line = null;
StringBuffer tmp = new StringBuffer();
System.out.println("the code is :" + conn.getResponseCode());
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
while ((line = in.readLine()) != null) {
tmp.append(line);
}
System.out.println("value line is: " + line +"& date is: " + header_date);
Scrape(String.valueOf(tmp)); // temp.toString()
in.close();
in = null;
url = null;
conn.disconnect();
conn = null;
} else {
System.out.println("something bad happened code <>200, debug from your server");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
To solve your Proxy problem you can try using Proxy as below
Proxy proxy= new Proxy(Proxy.Type.HTTP, new InetSocketAddress(<Proxy IP Address as String>, <Proxy Port Number as Integer>));
HttpURLConnection http_conn=(HttpURLConnection)request_url.openConnection(proxy);

Categories