Advertisement
Guest User

Untitled

a guest
Apr 24th, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 6.41 KB | None | 0 0
  1. package com.anuja.httpget;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.io.InputStreamReader;
  7.  
  8. import org.apache.http.HttpResponse;
  9. import org.apache.http.client.ClientProtocolException;
  10. import org.apache.http.client.HttpClient;
  11. import org.apache.http.client.methods.HttpGet;
  12. import org.apache.http.impl.client.DefaultHttpClient;
  13.  
  14. import android.app.Activity;
  15. import android.os.AsyncTask;
  16. import android.os.Bundle;
  17. import android.view.View;
  18. import android.view.View.OnClickListener;
  19. import android.widget.Button;
  20. import android.widget.EditText;
  21. import android.widget.Toast;
  22.  
  23. public class MyHttpGetProjectActivity extends Activity implements OnClickListener {
  24.  
  25.     private EditText usernameEditText;
  26.     private EditText passwordEditText;
  27.     private Button sendGetReqButton;
  28.  
  29.     /** Called when the activity is first created. */
  30.     @Override
  31.     public void onCreate(Bundle savedInstanceState) {
  32.         super.onCreate(savedInstanceState);
  33.         setContentView(R.layout.main);
  34.  
  35.         usernameEditText = (EditText) findViewById(R.id.main_username_editText);
  36.         passwordEditText = (EditText) findViewById(R.id.main_password_editText);
  37.  
  38.         sendGetReqButton = (Button) findViewById(R.id.main_sendGetReq_button);
  39.         sendGetReqButton.setOnClickListener(this);
  40.     }
  41.  
  42.     @Override
  43.     public void onClick(View v) {
  44.  
  45.         if(v.getId() == R.id.main_sendGetReq_button){
  46.  
  47.             // Get the values given in EditText fields
  48.             String givenUsername = usernameEditText.getText().toString();
  49.             String givenPassword = passwordEditText.getText().toString();
  50.             System.out.println("Givennames is :" + givenUsername + " Given password is :" + givenPassword);
  51.  
  52.             // Pass those values to connectWithHttpGet() method
  53.             connectWithHttpGet(givenUsername, givenPassword);
  54.         }      
  55.     }
  56.  
  57.     private void connectWithHttpGet(String givenUsername, String givenPassword) {
  58.  
  59.         // Connect with a server is a time consuming process.
  60.         //Therefore we use AsyncTask to handle it
  61.         // From the three generic types;
  62.         //First type relate with the argument send in execute()
  63.         //Second type relate with onProgressUpdate method which I haven't use in this code
  64.         //Third type relate with the return type of the doInBackground method, which also the input type of the onPostExecute method
  65.         class HttpGetAsyncTask extends AsyncTask<String, Void, String>{
  66.  
  67.             @Override
  68.             protected String doInBackground(String... params) {
  69.  
  70.                 // As you can see, doInBackground has taken an Array of Strings as the argument
  71.                 //We need to specifically get the givenUsername and givenPassword
  72.                 String paramUsername = params[0];
  73.                 String paramPassword = params[1];
  74.                 System.out.println("paramUsername" + paramUsername + " paramPassword is :" + paramPassword);
  75.  
  76.                 // Create an intermediate to connect with the Internet
  77.                 HttpClient httpClient = new DefaultHttpClient();
  78.  
  79.                 // Sending a GET request to the web page that we want
  80.                 // Because of we are sending a GET request, we have to pass the values through the URL
  81.                 HttpGet httpGet = new HttpGet("http://www.nirmana.lk/hec/android/getLogin.php?paramUsername=" + paramUsername + "&paramPassword=" + paramPassword);
  82.  
  83.                 try {
  84.                     // execute(); executes a request using the default context.
  85.                     // Then we assign the execution result to HttpResponse
  86.                     HttpResponse httpResponse = httpClient.execute(httpGet);
  87.                     System.out.println("httpResponse                    // getEntity() ; obtains the message entity of this response
  88.                     // getContent() ; creates a new InputStream object of the entity.
  89.                     // Now we need a readable source to read the byte stream that comes as the httpResponse
  90.                     InputStream inputStream = httpResponse.getEntity().getContent();
  91.  
  92.                     // We have a byte stream. Next step is to convert it to a Character stream
  93.                     InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
  94.  
  95.                     // Then we have to wraps the existing reader (InputStreamReader) and buffer the input
  96.                     BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
  97.  
  98.                     // InputStreamReader contains a buffer of bytes read from the source stream and converts these into characters as needed.
  99.                     //The buffer size is 8K
  100.                     //Therefore we need a mechanism to append the separately coming chunks in to one String element
  101.                     // We have to use a class that can handle modifiable sequence of characters for use in creating String
  102.                     StringBuilder stringBuilder = new StringBuilder();
  103.  
  104.                     String bufferedStrChunk = null;
  105.  
  106.                     // There may be so many buffered chunks. We have to go through each and every chunk of characters
  107.                     //and assign a each chunk to bufferedStrChunk String variable
  108.                     //and append that value one by one to the stringBuilder
  109.                     while((bufferedStrChunk = bufferedReader.readLine()) != null){
  110.                         stringBuilder.append(bufferedStrChunk);
  111.                     }
  112.  
  113.                     // Now we have the whole response as a String value.
  114.                     //We return that value then the onPostExecute() can handle the content
  115.                     System.out.println("Returninge of doInBackground :" + stringBuilder.toString());
  116.  
  117.                     // If the Username and Password match, it will return "working" as response
  118.                     // If the Username or Password wrong, it will return "invalid" as response                 
  119.                     return stringBuilder.toString();
  120.  
  121.                 } catch (ClientProtocolException cpe) {
  122.                     System.out.println("Exceptionrates caz of httpResponse :" + cpe);
  123.                     cpe.printStackTrace();
  124.                 } catch (IOException ioe) {
  125.                     System.out.println("Secondption generates caz of httpResponse :" + ioe);
  126.                     ioe.printStackTrace();
  127.                 }
  128.  
  129.                 return null;
  130.             }
  131.  
  132.             // Argument comes for this method according to the return type of the doInBackground() and
  133.             //it is the third generic type of the AsyncTask
  134.             @Override
  135.             protected void onPostExecute(String result) {
  136.                 super.onPostExecute(result);
  137.  
  138.                 if(result.equals("working")){
  139.                     Toast.makeText(getApplicationContext(), "HTTP GET is working...", Toast.LENGTH_LONG).show();
  140.                 }else{
  141.                     Toast.makeText(getApplicationContext(), "Invalid...", Toast.LENGTH_LONG).show();
  142.                 }              
  143.             }          
  144.         }
  145.  
  146.         // Initialize the AsyncTask class
  147.         HttpGetAsyncTask httpGetAsyncTask = new HttpGetAsyncTask();
  148.         // Parameter we pass in the execute() method is relate to the first generic type of the AsyncTask
  149.         // We are passing the connectWithHttpGet() method arguments to that
  150.         httpGetAsyncTask.execute(givenUsername, givenPassword);
  151.  
  152.     }
  153. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement