Android Open Source - FoodFinderApp Async Send Request






From Project

Back to project page FoodFinderApp.

License

The source code is released under:

GNU General Public License

If you think the Android project FoodFinderApp listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package cs499.examples.semesterproject;
/*w  w  w. j a  va  2  s. co m*/
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;

import org.apache.http.NameValuePair;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

public class AsyncSendRequest extends AsyncTask <String, String, String> 
{
  List<NameValuePair> requests;
  String url;
  Activity context;
  ProgressDialog progressDialog;
  boolean successful = false;
  
  public AsyncSendRequest (List<NameValuePair> requests, String url, Activity context)
  {
    this.requests = requests;
    this.url = url;
    this.context = context;
  }
  
  protected void onPreExecute() 
  {
    // TODO Auto-generated method stub
    progressDialog = new ProgressDialog(context);
      progressDialog.setMessage("Sending request to restaurant");
        progressDialog.show();  
    }
  
  @Override
  protected String doInBackground(String... arg0) 
  {
    // TODO Auto-generated method stub
    return this.postRestaurantInfo(this.url);
  }

  @SuppressWarnings("finally")
  public String postRestaurantInfo(String url)  // url is your json url
  {
    String s = null;
    HttpURLConnection conn = null;
    Log.d("Post", "In send request's post method now");
    try
    {
      Log.d("", "AsyncTask NameValuePairs");
      for (NameValuePair p: this.requests)
      {
        
        Log.d(p.getName(), p.getValue());
      }
      System.setProperty("http.keepAlive", "false");
      URL newUrl = new URL(this.url);
      Log.d("tag:", "Connecting to URL....");
      conn = (HttpURLConnection) newUrl.openConnection();
      conn.setReadTimeout(10000);
      conn.setConnectTimeout(15000);
      conn.setRequestMethod("POST");
      conn.setUseCaches(false);
      conn.setDoInput(true);
      conn.setDoOutput(true);
      
      Log.d("post: ", "Before post....");
      OutputStream os = conn.getOutputStream();
      BufferedWriter writer = new BufferedWriter(
              new OutputStreamWriter(os, "UTF-8"));
      writer.write(getQuery(this.requests));
      writer.flush();
      writer.close();
      os.close();
  
      conn.connect();
      int responseCode = conn.getResponseCode();
      Log.d("tag: ", "After posting....");
      Log.d("Http response: ", "" + responseCode); 
      
      InputStream is = conn.getInputStream();
      BufferedReader br = new BufferedReader(new InputStreamReader(is));
          StringBuilder sb = new StringBuilder();
          int value=0;
          int count = 0;
           
           // reads to the end of the stream 
          value = br.read();
           while( value != -1)
           {
              // converts int to character
              char c = (char)value;
              sb.append(c);
              count++;
              //System.out.println(c);
              value = br.read();
           }
           is.close();
          s = sb.toString();
          Log.d("tag: ", "Characters read: "+count+", Length of S: "+s.length() + "S itself: " + s);
      
    }
    catch (Exception e)
    {
      Log.e("Http Exception", "", e);
    }
    
    finally
    {
      conn.disconnect();
    }
    successful = true;
    return s;
  }
  
   private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException
     {
         StringBuilder result = new StringBuilder();
         boolean first = true;

         for (NameValuePair pair : params)
         {
             if (first)
                 first = false;
             else
                 result.append("&");

             result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
             result.append("=");
             result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
         }

         return result.toString();
     }

  @Override
  protected void onPostExecute(String result)
  {
    // TODO Auto-generated method stub
    if (this.progressDialog.isShowing())
      this.progressDialog.dismiss();
    if (successful)
      Toast.makeText(this.context, "Request was successfully submitted.", Toast.LENGTH_LONG).show();
  }

  
}




Java Source Code List

cs499.examples.semesterproject.AddItemsActivity.java
cs499.examples.semesterproject.AndroidFoodBankOwnerServlet.java
cs499.examples.semesterproject.AsyncAddItems.java
cs499.examples.semesterproject.AsyncAddPlace.java
cs499.examples.semesterproject.AsyncAddRestaurantToDB.java
cs499.examples.semesterproject.AsyncAuthenticateUser.java
cs499.examples.semesterproject.AsyncSearchAndShowPlaces.java
cs499.examples.semesterproject.AsyncSearchItems.java
cs499.examples.semesterproject.AsyncSendRequest.java
cs499.examples.semesterproject.AsyncViewRequests.java
cs499.examples.semesterproject.Constants.java
cs499.examples.semesterproject.DisplayMap.java
cs499.examples.semesterproject.DisplayMatchingPlaces.java
cs499.examples.semesterproject.DisplayPlaceItems.java
cs499.examples.semesterproject.DisplayPlace.java
cs499.examples.semesterproject.DisplayRequestActivity.java
cs499.examples.semesterproject.FoodBankOwnerActivity.java
cs499.examples.semesterproject.FoodOwnerOptions.java
cs499.examples.semesterproject.LoginActivity.java
cs499.examples.semesterproject.MainActivity.java
cs499.examples.semesterproject.OrganizationOptions.java
cs499.examples.semesterproject.OtherOwnerActivity.java
cs499.examples.semesterproject.QueryActivity.java
cs499.examples.semesterproject.ViewRequests.java
org.json.CDL.java
org.json.CookieList.java
org.json.Cookie.java
org.json.HTTPTokener.java
org.json.HTTP.java
org.json.JSONArray.java
org.json.JSONException.java
org.json.JSONML.java
org.json.JSONObject.java
org.json.JSONString.java
org.json.JSONStringer.java
org.json.JSONTokener.java
org.json.JSONWriter.java
org.json.Kim.java
org.json.Property.java
org.json.XMLTokener.java
org.json.XML.java
org.json.zip.BitInputStream.java
org.json.zip.BitOutputStream.java
org.json.zip.BitReader.java
org.json.zip.BitWriter.java
org.json.zip.Compressor.java
org.json.zip.Decompressor.java
org.json.zip.Huff.java
org.json.zip.JSONzip.java
org.json.zip.Keep.java
org.json.zip.MapKeep.java
org.json.zip.None.java
org.json.zip.PostMortem.java
org.json.zip.TrieKeep.java