Improving the Log in main Activity. Now make more sense.
authorgumartinm <gu.martinm@gmail.com>
Wed, 4 Jan 2012 06:02:14 +0000 (07:02 +0100)
committergumartinm <gu.martinm@gmail.com>
Wed, 4 Jan 2012 06:02:14 +0000 (07:02 +0100)
Trying to find out how to use a response handler for HttpClient
Work in progress.
By the way, I am committing white spaces. Sorry for that but I am in a hurry.

Android/Testing/Test3/src/de/android/test3/NextActivity.java
Android/Testing/Test3/src/de/android/test3/Test3Activity.java

index 16792d6..efd2eed 100644 (file)
@@ -18,6 +18,7 @@ import org.apache.http.HttpEntity;
 import org.apache.http.HttpResponse;
 import org.apache.http.HttpStatus;
 import org.apache.http.client.ClientProtocolException;
+import org.apache.http.client.ResponseHandler;
 import org.apache.http.client.methods.HttpGet;
 import org.json.JSONArray;
 import org.json.JSONException;
@@ -136,24 +137,33 @@ public class NextActivity extends Activity {
           
           @Override
           public void run()
-          {  
+          {
+                  ResponseHandler<StringBuilder> handler = new ResponseHandler<StringBuilder>() {
+                           public StringBuilder handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
+                               return sortResponse(response);
+                           }
+                       };
                   try {
                           final HttpGet httpGet = new HttpGet();
                           HttpResponse httpResponse = null;
-                  
+                          
+                          
                           httpGet.setHeader("Cookie", this.cookie);
                           try {
                                   httpGet.setURI(url.toURI()); 
-                                  httpResponse = httpClient.execute(httpGet);
-                                  httpResponse = httpClient.
-                                  sortResponse(httpResponse);
+                                  StringBuilder builder = httpClient.execute(httpGet, handler);
+                                  retrieveResponse(builder);
                           } catch (URISyntaxException e) {
                                   Log.e(TAG, "Error while creating URI from URL.", e);  
                           } catch (ClientProtocolException e) {
                                   Log.e(TAG, "Error while executing HTTP client connection.", e);
+                          } catch (UnsupportedEncodingException e)  {
+                                  Log.e(TAG, "Error  InputStreamReader.", e);
                           } catch (IOException e) {
                                   Log.e(TAG, "Error while executing HTTP client connection.", e);
-                          } finally {
+                          } catch (JSONException e) {
+                                  Log.e(TAG, "Error while parsing JSON response.", e);
+                       } finally {
                                   //Always release the resources whatever happens. Even when there is an 
                                   //unchecked exception which (by the way) is not expected. Be ready for the worse.
                                   NextActivity.this.httpClient.close();
@@ -163,50 +173,57 @@ public class NextActivity extends Activity {
                   }
           }
           
-          public void sortResponse(HttpResponse httpResponse) {
-                       switch (httpResponse.getStatusLine().getStatusCode()) {
-                       case HttpStatus.SC_OK:
+          public StringBuilder sortResponse(HttpResponse httpResponse) throws UnsupportedEncodingException, IllegalStateException, IOException {
+                  StringBuilder builder = null;
+                  
+                  switch (httpResponse.getStatusLine().getStatusCode()) {
+                  case HttpStatus.SC_OK:
                                //OK
                                HttpEntity entity = httpResponse.getEntity();
                                if (entity != null) {
-                                       InputStream instream = entity.getContent();
-                                       InputStreamReader instream = new InputStreamReader(entity.getContent(), entity.getContentEncoding().getValue());
-                                       BufferedReader reader = new BufferedReader(instream);
-                                       try {                           
-                                               StringBuilder builder = new StringBuilder();
+                                       InputStreamReader instream = null;
+                                       try {
+                                               instream = new InputStreamReader(entity.getContent(), entity.getContentEncoding().getValue());
+                                               BufferedReader reader = new BufferedReader(instream);                           
+                                               builder = new StringBuilder();
                                                String currentLine = null;
                                                currentLine = reader.readLine();
                                                while (currentLine != null) {
                                                        builder.append(currentLine).append("\n");
                                                        currentLine = reader.readLine();
                                                }
-                                               JSONTokener tokener = new JSONTokener(builder.toString());
-                                               JSONArray finalResult = new JSONArray(tokener);
-                                               for (int i = 0; i < finalResult.length(); i++) {
-                                                       JSONObject objects = finalResult.getJSONObject(i);
-                                                       downloadAds((Integer) objects.get("id"), (String)objects.get("domain"), (String)objects.get("link"));
-                                               }
-                                       } catch (UnsupportedEncodingException e) {
-                                               Log.e(TAG, "Error while parsing the JSON response from the RESTful Web Service.", e);
-                                       } catch (IllegalStateException e) {
-                                               Log.e(TAG, "Error while parsing the JSON response from the RESTful Web Service.", e);
-                                       } catch (IOException e) {
-                                               Log.e(TAG, "Error while parsing the JSON response from the RESTful Web Service.", e);
-                                       } catch (JSONException e) {
-                                               Log.e(TAG, "Error while parsing the JSON response from the RESTful Web Service.", e);
-                                       }
+                                       } finally {
+                                               if (instream != null) {
+                                                       try {
+                                                               instream.close();
+                                                       } catch (IOException e) {
+                                                               Log.e(TAG, "Error while closing InputStream.", e);
+                                                       }
+                                               }       
+                                       }                               
                                }
-                               break;
-                       case HttpStatus.SC_UNAUTHORIZED:
+                               break;                          
+                  case HttpStatus.SC_UNAUTHORIZED:
                                //ERROR IN USERNAME OR PASSWORD
-                               break;
-                       case HttpStatus.SC_BAD_REQUEST:
+                               break;                          
+                  case HttpStatus.SC_BAD_REQUEST:
                                //WHAT THE HECK ARE YOU DOING?
-                               break;
-                       default:
+                               break;                          
+                  default:
                                Log.e(TAG, "Error while retrieving the HTTP status line.");
-                               break;
-               }
+                               break;  
+                  }
+                  
+                  return builder;
+          }
+          
+          public void retrieveResponse(StringBuilder builder) throws JSONException {
+                  JSONTokener tokener = new JSONTokener(builder.toString());
+                  JSONArray finalResult = new JSONArray(tokener);
+                  for (int i = 0; i < finalResult.length(); i++) {
+                          JSONObject objects = finalResult.getJSONObject(i);
+                          downloadAds((Integer) objects.get("id"), (String)objects.get("domain"), (String)objects.get("link"));   
+                  }                            
           }
           
           public void downloadAds(Integer id, String domain, String link) {
index dec354a..ac7a90e 100644 (file)
@@ -30,6 +30,11 @@ import android.widget.EditText;
 
 public class Test3Activity extends Activity {
        private static final String TAG = "Test3Activity";
+       private static final String ENCODED = "UTF-8";
+       private static final String USERAGENTFIELD = "User-Agent";
+       private static final String USERAGENTVALUE = "MobieAds/1.0";
+       private static final String URLWEBSERVICE = "http://192.168.1.34/userfront.php/api/login/auth.json";
+       private static final String SETCOOKIEFIELD = "Set-Cookie";
        private StrictMode.ThreadPolicy currentPolicy;
        
     /** Called when the activity is first created. */
@@ -43,50 +48,48 @@ public class Test3Activity extends Activity {
     }
     
     public void onClickLogin(View v) {
-       final String URLAuth = "http://192.168.1.34/userfront.php/api/login/auth.json";
        final EditText password = (EditText) findViewById(R.id.password);
        final EditText username = (EditText) findViewById(R.id.username);
        final HttpClient httpClient = new DefaultHttpClient();
-               final HttpPost httpPost = new HttpPost(URLAuth);
+               final HttpPost httpPost = new HttpPost(URLWEBSERVICE);
                HttpEntity httpEntity = null;
                HttpResponse httpResponse = null;
-               final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
+               final List<NameValuePair> formParams = new ArrayList<NameValuePair>(2);
+
                
                //TODO: RESTful Web Service must use JSON instead of signin array :(
-        nameValuePairs.add(new BasicNameValuePair("signin[username]", username.getText().toString()));
-        nameValuePairs.add(new BasicNameValuePair("signin[password]", password.getText().toString()));
+               formParams.add(new BasicNameValuePair("signin[username]", username.getText().toString()));
+               formParams.add(new BasicNameValuePair("signin[password]", password.getText().toString()));
         try {
-                       httpEntity = new UrlEncodedFormEntity(nameValuePairs);
+                       httpEntity = new UrlEncodedFormEntity(formParams, ENCODED);
+                       httpPost.setEntity(httpEntity);
+               httpPost.setHeader(USERAGENTFIELD, USERAGENTVALUE);
+               httpResponse = httpClient.execute(httpPost);
                } catch (UnsupportedEncodingException e) {
                        Log.e(TAG, "Error while encoding POST parameters.", e);
-                       return;
-               }
-        httpPost.setEntity(httpEntity);
-        httpPost.setHeader("User-Agent", "MobieAds/1.0");
-        
-        try {
-                       httpResponse = httpClient.execute(httpPost);
-               } catch (ClientProtocolException e) {
+               } catch (ClientProtocolException e) {
                        Log.e(TAG, "Error while executing HTTP client connection.", e);
-                       httpClient.getConnectionManager().shutdown();
                        createErrorDialog(R.string.error_dialog_connection_error);
-                       return;
                } catch (IOException e) {
                        Log.e(TAG, "Error while executing HTTP client connection.", e);
-                       httpClient.getConnectionManager().shutdown();
                        createErrorDialog(R.string.error_dialog_connection_error);
-                       return;
+               } finally {
+                       httpClient.getConnectionManager().shutdown();
                }
         
-        switch (httpResponse.getStatusLine().getStatusCode()) {
+        if (httpResponse != null) {
+            switch (httpResponse.getStatusLine().getStatusCode()) {
                case HttpStatus.SC_OK:
-                       String cookie = httpResponse.getLastHeader("Set-Cookie").getValue();
-                               CookieManager.getInstance().setCookie("192.168.1.34/userfront.php",cookie);
-                               CookieSyncManager.getInstance().sync();
-                               //Go to the next activity
-                               httpClient.getConnectionManager().shutdown();
-                               StrictMode.setThreadPolicy(currentPolicy);
-                           this.startActivity(new Intent(Intent.ACTION_RUN));
+                       String cookie = httpResponse.getLastHeader(SETCOOKIEFIELD).getValue();
+                       if (cookie != null) {
+                               CookieManager.getInstance().setCookie("192.168.1.34/userfront.php",cookie);
+                                       CookieSyncManager.getInstance().sync();
+                                       //Go to the next activity
+                                       StrictMode.setThreadPolicy(currentPolicy);
+                                       this.startActivity(new Intent(Intent.ACTION_RUN));
+                       } else {
+                               Log.e(TAG, "There must be a weird issue with the server because... There is not cookie!!!!");
+                       }
                                break;
                        case HttpStatus.SC_UNAUTHORIZED:
                                //Username or password are incorrect
@@ -100,7 +103,8 @@ public class Test3Activity extends Activity {
                                Log.e(TAG, "Error while retrieving the HTTP status line.");
                                createErrorDialog(R.string.error_dialog_userpwd_error);
                                break;
-               }     
+            }          
+        } 
     }
     
     public void onClickCancel(View v) {