Android Open Source - rfcx-guardian-android Http Post Multipart






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;
//from   w  w  w.jav  a 2 s.  c  om
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;

import javax.net.ssl.HttpsURLConnection;

import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;

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

public class HttpPostMultipart {

  private static final String TAG = HttpPostMultipart.class.getSimpleName();
  private static final String NULL_EXC = "Exception thrown, but exception itself is null.";

    // need to make these longer and/or dynamic...
  private static int requestReadTimeout = 300000;
  private static int requestConnectTimeout = 300000;
  private static boolean useCaches = false;
  
  public static String doMultipartPost(String fullUrl, List<String[]> keyValueParameters, List<String[]> keyFilepathMimeAttachments) {
    
    /* fullUrl: url as a string
     * keyValueParameters: List of arrays of strings, with the indices: [fieldname, fieldvalue]
     * keyFilepathMimeAttachments: List of arrays of string, with indices [fieldname, filepath, file-mime]
     */
    
    MultipartEntity requestEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    try {
      for (String[] keyFilepathMime : keyFilepathMimeAttachments) {
        ContentBody contentBody = new FileBody(
            (new File(keyFilepathMime[1])),
            keyFilepathMime[1].substring(1+keyFilepathMime[1].lastIndexOf("/")), 
            keyFilepathMime[2], null);
        requestEntity.addPart(keyFilepathMime[0], contentBody);
      }
      for (String[] keyValue : keyValueParameters) {
        requestEntity.addPart(keyValue[0], new StringBody(URLEncoder.encode(keyValue[1], "UTF-8")));
      }
    } catch (UnsupportedEncodingException e) {
      Log.e(TAG,(e!=null) ? (e.getMessage() +" ||| "+ TextUtils.join(" | ", e.getStackTrace())) : NULL_EXC);
    } catch (Exception e) {
      Log.e(TAG,(e!=null) ? (e.getMessage() +" ||| "+ TextUtils.join(" | ", e.getStackTrace())) : NULL_EXC);
    }
    return executeMultipartPost(fullUrl, requestEntity);
  }
    
  private static String executeMultipartPost(String fullUrl, MultipartEntity requestEntity) {
    try {
        String inferredProtocol = fullUrl.substring(0, fullUrl.indexOf(":"));
      if (inferredProtocol.equals("http")) {
        return sendInsecurePostRequest((new URL(fullUrl)), requestEntity);
      } else if (inferredProtocol.equals("https")) {
        return sendSecurePostRequest((new URL(fullUrl)), requestEntity);
      } else {
        Log.e(TAG,"Inferred protocol was neither HTTP nor HTTPS.");
        return "";
      }
    } catch (MalformedURLException e) {
      Log.e(TAG,(e!=null) ? (e.getMessage() +" ||| "+ TextUtils.join(" | ", e.getStackTrace())) : NULL_EXC);
      Log.e(TAG,"Malformed URL");
      return "";
    }
  }
  
  private static String sendInsecurePostRequest(URL url, MultipartEntity entity) {
      try {
          HttpURLConnection conn = (HttpURLConnection) url.openConnection();
          conn.setReadTimeout(requestReadTimeout);
          conn.setConnectTimeout(requestConnectTimeout);
          conn.setRequestMethod("POST");
          conn.setUseCaches(useCaches);
          conn.setDoInput(true);
          conn.setDoOutput(true);
          conn.setRequestProperty("Connection", "Keep-Alive");
          conn.setFixedLengthStreamingMode((int) entity.getContentLength());
//          reqConn.addRequestProperty("Content-length", reqEntity.getContentLength()+"");
          conn.addRequestProperty(entity.getContentType().getName(), entity.getContentType().getValue());
          OutputStream outputStream = conn.getOutputStream();
          entity.writeTo(outputStream);
          outputStream.close();
          conn.connect();
        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
              Log.d(TAG, "Success");
          }
        return readResponseStream(conn.getInputStream());
      } catch (Exception e) {
        Log.e(TAG,(e!=null) ? (e.getMessage() +" ||| "+ TextUtils.join(" | ", e.getStackTrace())) : NULL_EXC);
      }
      return "";        
  }
  
  private static String sendSecurePostRequest(URL url, MultipartEntity entity) {
      try {
          HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
          conn.setReadTimeout(requestReadTimeout);
          conn.setConnectTimeout(requestConnectTimeout);
          conn.setRequestMethod("POST");
          conn.setUseCaches(useCaches);
          conn.setDoInput(true);
          conn.setDoOutput(true);
          conn.setRequestProperty("Connection", "Keep-Alive");
          conn.setFixedLengthStreamingMode((int) entity.getContentLength());
//          reqConn.addRequestProperty("Content-length", reqEntity.getContentLength()+"");
          conn.addRequestProperty(entity.getContentType().getName(), entity.getContentType().getValue());
          OutputStream outputStream = conn.getOutputStream();
          entity.writeTo(outputStream);
          outputStream.close();
          conn.connect();
        if (conn.getResponseCode() == HttpsURLConnection.HTTP_OK) {
              Log.d(TAG, "Success");
        }
          return readResponseStream(conn.getInputStream());
      } catch (Exception e) {
        Log.e(TAG,(e!=null) ? (e.getMessage() +" ||| "+ TextUtils.join(" | ", e.getStackTrace())) : NULL_EXC);
      }
      return "";        
  }

  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();
  } 
  
}




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