Android Open Source - rfcx-guardian-android Http Get






From Project

Back to project page rfcx-guardian-android.

License

The source code is released under:

Apache License

If you think the Android project rfcx-guardian-android 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 org.rfcx.guardian.utility;
/*www  .jav  a 2 s  .  c om*/
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;

import javax.net.ssl.HttpsURLConnection;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

public class HttpGet {

  private static final String TAG = HttpGet.class.getSimpleName();
  private static final String NULL_EXC = "Exception thrown, but exception itself is null.";
  private static final String DOWNLOAD_TIME_LABEL = "Download time: ";
  
  private boolean verboseLogging = false;
  
    // need to make these longer and/or dynamic
  // (dynamic is better but methods that reference them can't be static...)
  private static int requestReadTimeout = 600000;
  private static int requestConnectTimeout = 30000;
  private static boolean useCaches = false;
  
  
  public JSONObject getAsJson(String fullUrl, List<String[]> keyValueParameters) {
    long startTime = Calendar.getInstance().getTimeInMillis();
    String str = doGetString(fullUrl,keyValueParameters);
    if (verboseLogging) { Log.d(TAG,DOWNLOAD_TIME_LABEL+(Calendar.getInstance().getTimeInMillis()-startTime)+"ms"); }
    try {
      return (JSONObject) (new JSONParser()).parse(str);
    } catch (ParseException e) {
      Log.e(TAG,(e!=null) ? (e.getMessage() +" ||| "+ TextUtils.join(" | ", e.getStackTrace())) : NULL_EXC);
    }
    return null;
  }
  
  public JSONObject getAsJson(String fullUrl) {
    return getAsJson(fullUrl, (new ArrayList<String[]>()));
  }
  
  public List<JSONObject> getAsJsonArray(String fullUrl, List<String[]> keyValueParameters) {
    long startTime = Calendar.getInstance().getTimeInMillis();
    String str = doGetString(fullUrl,keyValueParameters);
    if (verboseLogging) { Log.d(TAG,DOWNLOAD_TIME_LABEL+(Calendar.getInstance().getTimeInMillis()-startTime)+"ms"); }
    try {
      List<JSONObject> jsonArray = new ArrayList<JSONObject>();
      JSONArray jsonAll = (JSONArray) (new JSONParser()).parse(str);
      Iterator jsonIterator = jsonAll.iterator();
      while (jsonIterator.hasNext()) {
        jsonArray.add((JSONObject) jsonIterator.next());
      }
      return jsonArray;

    } catch (ParseException e) {
      Log.e(TAG,(e!=null) ? (e.getMessage() +" ||| "+ TextUtils.join(" | ", e.getStackTrace())) : NULL_EXC);
    }
    return null;
  }
  
  public List<JSONObject> getAsJsonArray(String fullUrl) {
    return getAsJsonArray(fullUrl, (new ArrayList<String[]>()));
  }
  
  public String getAsString(String fullUrl, List<String[]> keyValueParameters) {
    long startTime = Calendar.getInstance().getTimeInMillis();
    String str = doGetString(fullUrl,keyValueParameters);
    if (verboseLogging) { Log.d(TAG,DOWNLOAD_TIME_LABEL+(Calendar.getInstance().getTimeInMillis()-startTime)+"ms"); }
    return str;
  }
  
  public String getAsString(String fullUrl) {
    return getAsString(fullUrl,(new ArrayList<String[]>()));
  }
  
  public boolean getAsFile(String fullUrl, List<String[]> keyValueParameters, String outputFileName, Context context) {
    long startTime = Calendar.getInstance().getTimeInMillis();
    StringBuilder url = (new StringBuilder()).append(fullUrl);
    if (keyValueParameters.size() > 0) url.append("?");
    for (String[] keyValue : keyValueParameters) {
      url.append(keyValue[0]).append("=").append(keyValue[1]).append("&");
    }
    if (verboseLogging) { Log.d(TAG,"HTTP GET: "+url.toString()); }
    FileOutputStream fileOutputStream = httpGetFileOutputStream(outputFileName,context);
    InputStream inputStream = httpGetFileInputStream(url.toString());
    if ((inputStream != null) && (fileOutputStream != null)) {
      writeFileResponseStream(inputStream,fileOutputStream);
      closeInputOutputStreams(inputStream,fileOutputStream);
      if (verboseLogging) { Log.d(TAG,DOWNLOAD_TIME_LABEL+(Calendar.getInstance().getTimeInMillis()-startTime)+"ms"); }
      return (new File(context.getFilesDir(), outputFileName)).exists();
    }
    return false;
  }
  
  public boolean getAsFile(String fullUrl, String outputFileName, Context context) {
    return getAsFile(fullUrl, (new ArrayList<String[]>()), outputFileName, context);
  }  
  
  private static String doGetString(String fullUrl, List<String[]> keyValueParameters) {
    StringBuilder url = (new StringBuilder()).append(fullUrl);
    if (keyValueParameters.size() > 0) url.append("?");
    for (String[] keyValue : keyValueParameters) {
      url.append(keyValue[0]).append("=").append(keyValue[1]).append("&");
    }
    Log.d(TAG,"HTTP GET: "+url.toString());
    return executeGet(url.toString());
  }
    
  private static String executeGet(String fullUrl) {
    try {
        String inferredProtocol = fullUrl.substring(0, fullUrl.indexOf(":"));
      if (inferredProtocol.equals("http")) {
        return sendInsecureGetRequest((new URL(fullUrl)));
      } else if (inferredProtocol.equals("https")) {
        return sendSecureGetRequest((new URL(fullUrl)));
      } else {
        Log.e(TAG, "Inferred protocol was neither HTTP nor HTTPS.");
      }
    } catch (MalformedURLException e) {
      Log.e(TAG,(e!=null) ? (e.getMessage() +" ||| "+ TextUtils.join(" | ", e.getStackTrace())) : NULL_EXC);
    }
    return null;
  }
  
  private static String sendInsecureGetRequest(URL url) {
      try {
          HttpURLConnection conn = (HttpURLConnection) url.openConnection();
          conn.setReadTimeout(requestReadTimeout);
          conn.setConnectTimeout(requestConnectTimeout);
          conn.setRequestMethod("GET");
          conn.setUseCaches(useCaches);
          conn.setDoInput(true);
          conn.setDoOutput(true);
          conn.setRequestProperty("Connection", "Keep-Alive");
          conn.connect();
        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
              return readResponseStream(conn.getInputStream());
          } else {
            Log.e(TAG, "HTTP Code: "+conn.getResponseCode());
          }
      } catch (Exception e) {
        Log.e(TAG,(e!=null) ? (e.getMessage() +" ||| "+ TextUtils.join(" | ", e.getStackTrace())) : NULL_EXC);
      }
      return null;        
  }
  
  private static String sendSecureGetRequest(URL url) {
      try {
          HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
          conn.setReadTimeout(requestReadTimeout);
          conn.setConnectTimeout(requestConnectTimeout);
          conn.setRequestMethod("GET");
          conn.setUseCaches(useCaches);
          conn.setDoInput(true);
          conn.setDoOutput(true);
          conn.setRequestProperty("Connection", "Keep-Alive");
          conn.connect();
        if (conn.getResponseCode() == HttpsURLConnection.HTTP_OK) {
              return readResponseStream(conn.getInputStream());
          } else {
            Log.e(TAG, "HTTP Code: "+conn.getResponseCode());
          }
      } catch (Exception e) {
        Log.e(TAG,(e!=null) ? (e.getMessage() +" ||| "+ TextUtils.join(" | ", e.getStackTrace())) : NULL_EXC);
      }
      return null;    
  }

  private static String readResponseStream(InputStream inputStream) {
      BufferedReader bufferedReader = null;
      StringBuilder stringBuilder = new StringBuilder();
      try {
          bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
          String currentLine = "";
          while ((currentLine = bufferedReader.readLine()) != null) {
              stringBuilder.append(currentLine);
          }
      } catch (IOException e) {
        Log.e(TAG,(e!=null) ? (e.getMessage() +" ||| "+ TextUtils.join(" | ", e.getStackTrace())) : NULL_EXC);
      } finally {
          if (bufferedReader != null) {
              try {
                  bufferedReader.close();
              } catch (IOException e) {
                Log.e(TAG,(e!=null) ? (e.getMessage() +" ||| "+ TextUtils.join(" | ", e.getStackTrace())) : NULL_EXC);
              }
          }
      }
      return stringBuilder.toString();
  } 

  private static void writeFileResponseStream(InputStream inputStream, FileOutputStream fileOutputStream) {
    try {
      byte[] buffer = new byte[8192];
      int bufferLength = 0;
      while ((bufferLength = inputStream.read(buffer)) != -1) {
        fileOutputStream.write(buffer, 0, bufferLength);
      }
    } catch (IOException e) {
      Log.e(TAG,(e!=null) ? (e.getMessage() +" ||| "+ TextUtils.join(" | ", e.getStackTrace())) : NULL_EXC);
    }
  }
  
  private static void closeInputOutputStreams(InputStream inputStream, FileOutputStream fileOutputStream) {
    try {
      inputStream.close();
      fileOutputStream.flush();
      fileOutputStream.close();
    } catch (IOException e) {
      Log.e(TAG,(e!=null) ? (e.getMessage() +" ||| "+ TextUtils.join(" | ", e.getStackTrace())) : NULL_EXC);
    }
  }
  
  private static FileOutputStream httpGetFileOutputStream(String fileName, Context context) {
    File targetFile = new File(context.getFilesDir().toString()+"/"+fileName);
    if (targetFile.exists()) { targetFile.delete(); }
    try {
      return context.openFileOutput(fileName, Context.MODE_WORLD_READABLE|Context.MODE_WORLD_WRITEABLE);
    } catch (FileNotFoundException e) {
      Log.e(TAG,(e!=null) ? (e.getMessage() +" ||| "+ TextUtils.join(" | ", e.getStackTrace())) : NULL_EXC);
    }
    return null;
  }
  
  private static InputStream httpGetFileInputStream(String fullUrl) {
      String inferredProtocol = fullUrl.substring(0, fullUrl.indexOf(":"));
      try {
      if (inferredProtocol.equals("http")) {
        HttpsURLConnection conn = (HttpsURLConnection) (new URL(fullUrl)).openConnection();
            conn.setReadTimeout(requestReadTimeout);
            conn.setConnectTimeout(requestConnectTimeout);
            conn.setRequestMethod("GET");
            conn.setUseCaches(useCaches);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.connect();
            if (conn.getResponseCode() == HttpsURLConnection.HTTP_OK) {
              return conn.getInputStream();
            } else {
              Log.e(TAG, "HTTP Code: "+conn.getResponseCode());
            }
      } else if (inferredProtocol.equals("https")) {
        HttpURLConnection conn = (HttpURLConnection) (new URL(fullUrl)).openConnection();
            conn.setReadTimeout(requestReadTimeout);
            conn.setConnectTimeout(requestConnectTimeout);
            conn.setRequestMethod("GET");
            conn.setUseCaches(useCaches);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.connect();
            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
              return conn.getInputStream();
            } else {
              Log.e(TAG, "HTTP Code: "+conn.getResponseCode());
            }
      } else {
        Log.e(TAG,"Inferred protocol was neither HTTP nor HTTPS.");
      }
      } catch (MalformedURLException e) {
        Log.e(TAG,(e!=null) ? (e.getMessage() +" ||| "+ TextUtils.join(" | ", e.getStackTrace())) : NULL_EXC);
      } catch (IOException e) {
        Log.e(TAG,(e!=null) ? (e.getMessage() +" ||| "+ TextUtils.join(" | ", e.getStackTrace())) : NULL_EXC);
      }
    return null;
  }

  public void useVerboseLogging(boolean yesNo) {
    this.verboseLogging = yesNo;
  }
  
}




Java Source Code List

net.sourceforge.javaFlacEncoder.ArrayRecycler.java
net.sourceforge.javaFlacEncoder.BlockEncodeRequest.java
net.sourceforge.javaFlacEncoder.BlockThreadManager.java
net.sourceforge.javaFlacEncoder.CRC16.java
net.sourceforge.javaFlacEncoder.CRC8.java
net.sourceforge.javaFlacEncoder.ChannelData.java
net.sourceforge.javaFlacEncoder.EncodedElement_32.java
net.sourceforge.javaFlacEncoder.EncodedElement.java
net.sourceforge.javaFlacEncoder.EncodingConfiguration.java
net.sourceforge.javaFlacEncoder.FLACEncoder.java
net.sourceforge.javaFlacEncoder.FLACFileOutputStream.java
net.sourceforge.javaFlacEncoder.FLACOutputStream.java
net.sourceforge.javaFlacEncoder.FLACStreamController.java
net.sourceforge.javaFlacEncoder.FLACStreamIdentifier.java
net.sourceforge.javaFlacEncoder.FLACStreamOutputStream.java
net.sourceforge.javaFlacEncoder.FLAC_ConsoleFileEncoder.java
net.sourceforge.javaFlacEncoder.FLAC_FileEncoder.java
net.sourceforge.javaFlacEncoder.FLAC_MD5.java
net.sourceforge.javaFlacEncoder.FrameHeader.java
net.sourceforge.javaFlacEncoder.FrameThread.java
net.sourceforge.javaFlacEncoder.Frame.java
net.sourceforge.javaFlacEncoder.LPC.java
net.sourceforge.javaFlacEncoder.MetadataBlockHeader.java
net.sourceforge.javaFlacEncoder.MetadataBlockStreamInfo.java
net.sourceforge.javaFlacEncoder.RiceEncoder.java
net.sourceforge.javaFlacEncoder.StreamConfiguration.java
net.sourceforge.javaFlacEncoder.Subframe_Constant.java
net.sourceforge.javaFlacEncoder.Subframe_Fixed.java
net.sourceforge.javaFlacEncoder.Subframe_LPC.java
net.sourceforge.javaFlacEncoder.Subframe_Verbatim.java
net.sourceforge.javaFlacEncoder.Subframe.java
net.sourceforge.javaFlacEncoder.UTF8Modified.java
org.rfcx.guardian.RfcxGuardianPrefs.java
org.rfcx.guardian.RfcxGuardian.java
org.rfcx.guardian.activity.MainActivity.java
org.rfcx.guardian.activity.PrefsActivity.java
org.rfcx.guardian.api.ApiCore.java
org.rfcx.guardian.audio.AudioCore.java
org.rfcx.guardian.database.AlertDb.java
org.rfcx.guardian.database.AudioDb.java
org.rfcx.guardian.database.DeviceStateDb.java
org.rfcx.guardian.database.SmsDb.java
org.rfcx.guardian.device.AirplaneMode.java
org.rfcx.guardian.device.CpuUsage.java
org.rfcx.guardian.device.DeviceState.java
org.rfcx.guardian.intentservice.ApiCheckInTriggerIntentService.java
org.rfcx.guardian.intentservice.AudioEncodeIntentService.java
org.rfcx.guardian.intentservice.ServiceMonitorIntentService.java
org.rfcx.guardian.receiver.AirplaneModeReceiver.java
org.rfcx.guardian.receiver.BootReceiver.java
org.rfcx.guardian.receiver.ConnectivityReceiver.java
org.rfcx.guardian.receiver.SmsReceiver.java
org.rfcx.guardian.service.ApiCheckInService.java
org.rfcx.guardian.service.AudioCaptureService.java
org.rfcx.guardian.service.CarrierCodeService.java
org.rfcx.guardian.service.DeviceStateService.java
org.rfcx.guardian.telecom.CarrierInteraction.java
org.rfcx.guardian.utility.DateTimeUtils.java
org.rfcx.guardian.utility.DeviceGuid.java
org.rfcx.guardian.utility.ExtAudioRecorderModified.java
org.rfcx.guardian.utility.FileUtils.java
org.rfcx.guardian.utility.HttpGet.java
org.rfcx.guardian.utility.HttpPostMultipart.java
org.rfcx.guardian.utility.TimeOfDay.java