Example usage for javax.net.ssl HttpsURLConnection setHostnameVerifier

List of usage examples for javax.net.ssl HttpsURLConnection setHostnameVerifier

Introduction

In this page you can find the example usage for javax.net.ssl HttpsURLConnection setHostnameVerifier.

Prototype

public void setHostnameVerifier(HostnameVerifier v) 

Source Link

Document

Sets the HostnameVerifier for this instance.

Usage

From source file:org.apache.tez.engine.common.shuffle.impl.Fetcher.java

@VisibleForTesting
protected HttpURLConnection openConnection(URL url) throws IOException {
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    if (sslShuffle) {
        HttpsURLConnection httpsConn = (HttpsURLConnection) conn;
        try {/*from   ww w .  ja va 2  s. c o  m*/
            httpsConn.setSSLSocketFactory(sslFactory.createSSLSocketFactory());
        } catch (GeneralSecurityException ex) {
            throw new IOException(ex);
        }
        httpsConn.setHostnameVerifier(sslFactory.getHostnameVerifier());
    }
    return conn;
}

From source file:org.comixwall.pffw.GraphsBase.java

/**
 * Run the controller task.//from  ww w  .j a  v  a 2 s.c  o m
 * We fetch the graphs using secure http, or fall back to plain http if secure connection fails.
 * <p>
 * Note that the PFFW uses a self-signed server certificate. So the code should trust that certificate
 * and not reject the hostname.
 *
 * @return True on success, false on failure.
 */
@Override
public boolean executeTask() {
    Boolean retval = true;
    try {
        String output = controller.execute("symon", "RenderLayout", mLayout, mGraphWidth, mGraphHeight);

        JSONArray jsonArray = new JSONArray(output);
        mGraphsJsonObject = new JSONObject(jsonArray.get(0).toString());

        Iterator<String> it = mGraphsJsonObject.keys();
        while (it.hasNext()) {
            String title = it.next();
            String file = mGraphsJsonObject.getString(title);

            try {
                InputStream stream = null;

                try {
                    String outputGraph = controller.execute("symon", "GetGraph", file);
                    String base64Graph = new JSONArray(outputGraph).get(0).toString();
                    stream = new ByteArrayInputStream(Base64.decode(base64Graph, Base64.DEFAULT));

                } catch (Exception e) {
                    e.printStackTrace();
                    logger.warning("SSH graph connection exception: " + e.toString());
                }

                // Try secure http if ssh fails
                if (stream == null) {
                    // 1540861800_404e00f4044d07242a77f802e457f774
                    String hash = file.substring(file.indexOf('_') + 1);

                    try {
                        // Using https here gives: CertPathValidatorException: Trust anchor for certification path not found.
                        // So we should trust the PFFW server crt and hostname
                        URL secureUrl = new URL("https://" + controller.getHost() + "/symon/graph.php?" + hash);

                        HttpsURLConnection secureUrlConn = (HttpsURLConnection) secureUrl.openConnection();

                        // Tell the URLConnection to use a SocketFactory from our SSLContext
                        secureUrlConn.setSSLSocketFactory(sslContext.getSocketFactory());

                        // Install the PFFW host verifier
                        secureUrlConn.setHostnameVerifier(hostnameVerifier);

                        logger.finest("Using secure http: " + secureUrl.toString());

                        // ATTENTION: Setting a timeout value enables SocketTimeoutException, set both timeouts
                        secureUrlConn.setConnectTimeout(5000);
                        secureUrlConn.setReadTimeout(5000);
                        logger.finest("Secure URL connection timeout values: "
                                + secureUrlConn.getConnectTimeout() + ", " + secureUrlConn.getReadTimeout());

                        stream = secureUrlConn.getInputStream();

                    } catch (Exception e) {
                        e.printStackTrace();
                        logger.warning("Secure URL connection exception: " + e.toString());
                    }

                    // Try plain http if secure http fails
                    if (stream == null) {
                        // ATTENTION: Don't use try-catch here, catch in the outer exception handling
                        URL plainUrl = new URL("http://" + controller.getHost() + "/symon/graph.php?" + hash);

                        HttpURLConnection plainUrlConn = (HttpURLConnection) plainUrl.openConnection();

                        logger.finest("Using plain http: " + plainUrlConn.toString());

                        // ATTENTION: Setting a timeout value enables SocketTimeoutException, set both timeouts
                        plainUrlConn.setConnectTimeout(5000);
                        plainUrlConn.setReadTimeout(5000);
                        logger.finest("Plain URL connection timeout values: " + plainUrlConn.getConnectTimeout()
                                + ", " + plainUrlConn.getReadTimeout());

                        stream = plainUrlConn.getInputStream();
                    }
                }

                Bitmap bmp = BitmapFactory.decodeStream(stream);
                setBitmap(title, bmp);

            } catch (Exception e) {
                // We are especially interested in SocketTimeoutException, but catch all
                e.printStackTrace();
                logger.info("GraphsBase doInBackground exception: " + e.toString());
                // We should break out of while loop on exception, because all conn attempts have failed
                break;
            }
        }

        output = controller.execute("pf", "GetReloadRate");

        int timeout = Integer.parseInt(new JSONArray(output).get(0).toString());
        mRefreshTimeout = timeout < 10 ? 10 : timeout;

    } catch (Exception e) {
        e.printStackTrace();
        logger.warning("doInBackground exception: " + e.toString());
        retval = false;
    }
    return retval;
}

From source file:org.kontalk.client.ClientHTTPConnection.java

private void setupClient(HttpsURLConnection conn, boolean acceptAnyCertificate)
        throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException,
        KeyManagementException, NoSuchProviderException, IOException {

    // bug caused by Lighttpd
    //conn.setRequestProperty("Expect", "100-continue");
    conn.setConnectTimeout(CONNECT_TIMEOUT);
    conn.setReadTimeout(READ_TIMEOUT);
    conn.setDoInput(true);//from w ww.ja v  a2  s.  c o  m
    conn.setSSLSocketFactory(setupSSLSocketFactory(mContext, mPrivateKey, mCertificate, acceptAnyCertificate));
    if (acceptAnyCertificate)
        conn.setHostnameVerifier(new AllowAllHostnameVerifier());
}

From source file:com.polyvi.xface.extension.filetransfer.XFileTransferExt.java

/**
 * ?Http/* w  w  w.ja va 2s  .co m*/
 * @param url           ??
 * @param trustEveryone 
 */
private HttpURLConnection getURLConnection(URL url, boolean trustEveryone) throws IOException {
    HttpURLConnection conn = null;
    // ?URL??HTTP
    if (url.getProtocol().toLowerCase().equals("https")) {
        // HTTPS. ????
        if (!trustEveryone) {
            conn = (HttpsURLConnection) url.openConnection();
        } else {
            trustAllHosts();
            HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
            // ?? hostnameVerifier
            mDefaultHostnameVerifier = https.getHostnameVerifier();
            https.setHostnameVerifier(DO_NOT_VERIFY);
            conn = https;
        }
    }
    // HTTP
    else {
        conn = (HttpURLConnection) url.openConnection();
    }
    return conn;
}

From source file:org.openmrs.module.rheapocadapter.handler.ConnectionHandler.java

public String[] callPostAndPut(String stringUrl, String body, String method) {
    try {/*from   www .  ja va  2  s  . co  m*/
        // Setup connection
        URL url = new URL(stringUrl);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod(method.toUpperCase());
        conn.setDoInput(true);
        // This is important to get the connection to use our trusted
        // certificate
        conn.setSSLSocketFactory(sslFactory);

        addHTTPBasicAuthProperty(conn);
        conn.setConnectTimeout(timeOut);
        // bug fixing for SSL error, this is a temporary fix, need to find a
        // long term one
        conn.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });

        OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
        log.error("body" + body);
        out.write(body);
        out.close();
        conn.connect();
        String result = "";
        int code = conn.getResponseCode();

        if (code == 201) {
            result = "Saved succefully";
        } else {
            result = "Not Saved";
        }
        conn.disconnect();

        return new String[] { code + "", result };
    } catch (MalformedURLException e) {
        e.printStackTrace();
        log.error("MalformedURLException while callPostAndPut " + e.getMessage());
        return new String[] { 400 + "", e.getMessage() };
    } catch (IOException e) {
        e.printStackTrace();
        log.error("IOException while callPostAndPut " + e.getMessage());
        return new String[] { 600 + "", e.getMessage() };
    }
}

From source file:org.belio.service.gateway.AirtelCharging.java

private String sendXmlOverPost(String url, String xml) {
    StringBuffer result = new StringBuffer();
    try {/* w  w  w .ja  v  a 2  s.  co  m*/
        Launcher.LOG.info("======================xml==============");

        Launcher.LOG.info(xml.toString());

        //            String userPassword = "roamtech_KE:roamtech _KE!ibm123";
        //            URL url2 = new URL("https://41.223.58.133:8443/ChargingServiceFlowWeb/sca/ChargingExport1");

        String userPassword = "" + networkproperties.getProperty("air_info_u") + ":"
                + networkproperties.getProperty("air_info_p");
        URL url2 = new URL(url);

        // URLConnection urlc =  url.openConnection();
        URLConnection urlc = url2.openConnection();
        HttpsURLConnection conn = (HttpsURLConnection) urlc;
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("SOAPAction", "run");

        //            urlc.setDoOutput(true);
        //            urlc.setUseCaches(false);
        //            urlc.setAllowUserInteraction(false);
        conn.setRequestProperty("Authorization", "Basic " + new Base64().encode(userPassword.getBytes()));
        conn.setRequestProperty("Content-Type", "text/xml");

        conn.setHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });

        // Write post data
        DataOutputStream out = new DataOutputStream(conn.getOutputStream());
        out.writeBytes(xml);
        out.flush();
        out.close();
        BufferedReader aiResult = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        StringBuffer responseMessage = new StringBuffer();
        while ((line = aiResult.readLine()) != null) {
            responseMessage.append(line);
        }
        System.out.println(responseMessage);

        //urlc.s("POST");  
        //  urlc.setRequestProperty("SOAPAction", SOAP_ACTION);

        urlc.connect();

    }

    catch (MalformedURLException ex) {
        Logger.getLogger(AirtelCharging.class

                .getName()).log(Level.SEVERE, null, ex);
    }

    catch (IOException ex) {
        Logger.getLogger(AirtelCharging.class

                .getName()).log(Level.SEVERE, null, ex);
    }
    return result.toString();

    //        try {
    //            // String url = "https://selfsolve.apple.com/wcResults.do";
    //            HttpClient client = new DefaultHttpClient();
    //            HttpPost post = new HttpPost("https://41.223.58.133:8443/ChargingServiceFlowWeb/sca/ChargingExport1");
    //            // add header
    //            post.setHeader("User-Agent", USER_AGENT);
    //            post.setHeader("Content-type:", " text/xml");
    //            post.setHeader("charset", "utf-8");
    //            post.setHeader("Accept:", ",text/xml");
    //            post.setHeader("Cache-Control:", " no-cache");
    //            post.setHeader("Pragma:", " no-cache");
    //            post.setHeader("SOAPAction:", "run");
    //            post.setHeader("Content-length:", "xml");
    //            
    ////            String encoding = new Base64().encode((networkproperties.getProperty("air_charge_n") + ":"
    ////                    + networkproperties.getProperty("air_charge_p")).getBytes());
    //            String encoding = new Base64().encode( ("roamtech_KE:roamtech _KE!ibm123").getBytes());
    //            
    //            post.setHeader("Authorization", "Basic " + encoding);
    //
    //            // post.setHeader("Authorization: Basic ", "base64_encode(credentials)");
    //            List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
    //            
    //            urlParameters.add(new BasicNameValuePair("xml", xml));
    //            
    //            System.out.println("\n============================ : " + url);
    //
    ////            urlParameters.add(new BasicNameValuePair("srcCode", ""));
    ////            urlParameters.add(new BasicNameValuePair("phone", ""));
    ////            urlParameters.add(new BasicNameValuePair("contentId", ""));
    ////            urlParameters.add(new BasicNameValuePair("itemName", ""));
    ////            urlParameters.add(new BasicNameValuePair("contentDescription", ""));
    ////            urlParameters.add(new BasicNameValuePair("actualPrice", ""));
    ////            urlParameters.add(new BasicNameValuePair("contentMediaType", ""));
    ////            urlParameters.add(new BasicNameValuePair("contentUrl", ""));
    //            post.setEntity(new UrlEncodedFormEntity(urlParameters));
    //            
    //            HttpResponse response = client.execute(post);
    //            Launcher.LOG.info("\nSending 'POST' request to URL : " + url);
    //            Launcher.LOG.info("Post parameters : " + post.getEntity());
    //            Launcher.LOG.info("Response Code : "
    //                    + response.getStatusLine().getStatusCode());
    //            
    //            BufferedReader rd = new BufferedReader(
    //                    new InputStreamReader(response.getEntity().getContent()));
    //            
    //            String line = "";
    //            while ((line = rd.readLine()) != null) {
    //                result.append(line);
    //            }
    //            
    //            System.out.println(result.toString());
    //        } catch (UnsupportedEncodingException ex) {
    //            Launcher.LOG.info(ex.getMessage());
    //        } catch (IOException ex) {
    //            Launcher.LOG.info(ex.getMessage());
    //        }
}

From source file:org.apache.hadoop.mapreduce.task.reduce.Fetcher.java

@VisibleForTesting
protected synchronized void openConnection(URL url) throws IOException {
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    if (sslShuffle) {
        HttpsURLConnection httpsConn = (HttpsURLConnection) conn;
        try {//w w w. ja  v  a2  s. com
            httpsConn.setSSLSocketFactory(sslFactory.createSSLSocketFactory());
        } catch (GeneralSecurityException ex) {
            throw new IOException(ex);
        }
        httpsConn.setHostnameVerifier(sslFactory.getHostnameVerifier());
    }
    connection = conn;
}

From source file:org.matrix.androidsdk.db.MXMediaWorkerTask.java

@Override
protected Bitmap doInBackground(Integer... params) {
    try {/*w ww  .  j  a va2 s  .co m*/
        // check the in-memory cache
        String key = mUrl;

        URL url = new URL(mUrl);
        Log.d(LOG_TAG, "BitmapWorkerTask open >>>>> " + mUrl);

        InputStream stream = null;
        Bitmap bitmap = null;

        long filelen = -1;
        URLConnection connection = null;

        try {
            connection = url.openConnection();

            if (mHsConfig != null && connection instanceof HttpsURLConnection) {
                // Add SSL Socket factory.
                HttpsURLConnection sslConn = (HttpsURLConnection) connection;
                try {
                    sslConn.setSSLSocketFactory(CertUtil.newPinnedSSLSocketFactory(mHsConfig));
                    sslConn.setHostnameVerifier(CertUtil.newHostnameVerifier(mHsConfig));
                } catch (Exception e) {
                    Log.e(LOG_TAG, "doInBackground SSL exception " + e.getLocalizedMessage());
                }
            }

            // add a timeout to avoid infinite loading display.
            connection.setReadTimeout(10 * 1000);
            filelen = connection.getContentLength();
            stream = connection.getInputStream();
        } catch (FileNotFoundException e) {
            InputStream errorStream = ((HttpsURLConnection) connection).getErrorStream();

            if (null != errorStream) {
                try {
                    BufferedReader streamReader = new BufferedReader(
                            new InputStreamReader(errorStream, "UTF-8"));
                    StringBuilder responseStrBuilder = new StringBuilder();

                    String inputStr;

                    while ((inputStr = streamReader.readLine()) != null) {
                        responseStrBuilder.append(inputStr);
                    }

                    mErrorAsJsonElement = new JsonParser().parse(responseStrBuilder.toString());
                } catch (Exception ee) {
                }
            }

            Log.d(LOG_TAG, "MediaWorkerTask " + mUrl + " does not exist");
            if (isBitmapDownload()) {
                bitmap = BitmapFactory.decodeResource(mApplicationContext.getResources(),
                        android.R.drawable.ic_menu_gallery);

                // if some medias are not found
                // do not try to reload them until the next application launch.
                synchronized (mFileNotFoundUrlsList) {
                    mFileNotFoundUrlsList.add(mUrl);
                }
            }
        }

        sendStart();

        String filename = MXMediaWorkerTask.buildFileName(mUrl, mMimeType) + ".tmp";
        FileOutputStream fos = new FileOutputStream(new File(mDirectoryFile, filename));

        // a bitmap has been provided
        if (null != bitmap) {
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        } else {
            try {
                int totalDownloaded = 0;

                byte[] buf = new byte[1024 * 32];
                int len;
                while ((len = stream.read(buf)) != -1) {
                    fos.write(buf, 0, len);

                    totalDownloaded += len;

                    int progress = 0;

                    if (filelen > 0) {
                        if (totalDownloaded >= filelen) {
                            progress = 99;
                        } else {
                            progress = (int) (totalDownloaded * 100 / filelen);
                        }
                    } else {
                        progress = -1;
                    }

                    Log.d(LOG_TAG, "download " + progress + " (" + mUrl + ")");

                    publishProgress(mProgress = progress);
                }

                mProgress = 100;
            } catch (OutOfMemoryError outOfMemoryError) {
                Log.e(LOG_TAG, "MediaWorkerTask : out of memory");
            } catch (Exception e) {
                Log.e(LOG_TAG, "MediaWorkerTask fail to read image " + e.getMessage());
            }

            close(stream);
        }

        fos.flush();
        fos.close();

        // the file has been successfully downloaded
        if (mProgress == 100) {
            try {
                File originalFile = new File(mDirectoryFile, filename);
                String newFileName = MXMediaWorkerTask.buildFileName(mUrl, mMimeType);
                File newFile = new File(mDirectoryFile, newFileName);
                if (newFile.exists()) {
                    // Or you could throw here.
                    mApplicationContext.deleteFile(newFileName);
                }
                originalFile.renameTo(newFile);
            } catch (Exception e) {
            }
        }

        Log.d(LOG_TAG, "download is done (" + mUrl + ")");

        synchronized (mPendingDownloadByUrl) {
            mPendingDownloadByUrl.remove(mUrl);
        }

        // load the bitmap from the cache
        if (isBitmapDownload()) {
            // get the bitmap from the filesytem
            if (null == bitmap) {
                bitmap = MXMediaWorkerTask.bitmapForURL(mApplicationContext, mDirectoryFile, key, mRotation,
                        mMimeType);
            }
        }

        return bitmap;
    } catch (Exception e) {
        // remove the image from the loading one
        // else the loading will be stucked (and never be tried again).
        synchronized (mPendingDownloadByUrl) {
            mPendingDownloadByUrl.remove(mUrl);
        }
        Log.e(LOG_TAG, "Unable to load bitmap: " + e);
        return null;
    }
}

From source file:org.skt.runtime.html5apis.file.FileTransfer.java

/**
 * Uploads the specified file to the server URL provided using an HTTP multipart request.
 * @param source        Full path of the file on the file system
 * @param target        URL of the server to receive the file
 * @param args          JSON Array of args
 *
 * args[2] fileKey       Name of file request parameter
 * args[3] fileName      File name to be used on server
 * args[4] mimeType      Describes file content type
 * args[5] params        key:value pairs of user-defined parameters
 * @return FileUploadResult containing result of upload request
 */// ww  w.ja v  a 2  s.  co  m
private PluginResult upload(String source, String target, JSONArray args) {
    Log.d(LOG_TAG, "upload " + source + " to " + target);

    HttpURLConnection conn = null;
    try {
        // Setup the options
        String fileKey = getArgument(args, 2, "file");
        String fileName = getArgument(args, 3, "image.jpg");
        String mimeType = getArgument(args, 4, "image/jpeg");
        JSONObject params = args.optJSONObject(5);
        if (params == null) {
            params = new JSONObject();
        }
        boolean trustEveryone = args.optBoolean(6);
        boolean chunkedMode = args.optBoolean(7) || args.isNull(7); //Always use chunked mode unless set to false as per API

        Log.d(LOG_TAG, "fileKey: " + fileKey);
        Log.d(LOG_TAG, "fileName: " + fileName);
        Log.d(LOG_TAG, "mimeType: " + mimeType);
        Log.d(LOG_TAG, "params: " + params);
        Log.d(LOG_TAG, "trustEveryone: " + trustEveryone);
        Log.d(LOG_TAG, "chunkedMode: " + chunkedMode);

        // Create return object
        FileUploadResult result = new FileUploadResult();

        // Get a input stream of the file on the phone
        FileInputStream fileInputStream = (FileInputStream) getPathFromUri(source);

        DataOutputStream dos = null;

        int bytesRead, bytesAvailable, bufferSize;
        long totalBytes;
        byte[] buffer;
        int maxBufferSize = 8096;

        //------------------ CLIENT REQUEST
        // open a URL connection to the server
        URL url = new URL(target);

        // Open a HTTP connection to the URL based on protocol
        if (url.getProtocol().toLowerCase().equals("https")) {
            // Using standard HTTPS connection. Will not allow self signed certificate
            if (!trustEveryone) {
                conn = (HttpsURLConnection) url.openConnection();
            }
            // Use our HTTPS connection that blindly trusts everyone.
            // This should only be used in debug environments
            else {
                // Setup the HTTPS connection class to trust everyone
                trustAllHosts();
                HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
                // Save the current hostnameVerifier
                defaultHostnameVerifier = https.getHostnameVerifier();
                // Setup the connection not to verify hostnames
                https.setHostnameVerifier(DO_NOT_VERIFY);
                conn = https;
            }
        }
        // Return a standard HTTP connection
        else {
            conn = (HttpURLConnection) url.openConnection();
        }

        // Allow Inputs
        conn.setDoInput(true);

        // Allow Outputs
        conn.setDoOutput(true);

        // Don't use a cached copy.
        conn.setUseCaches(false);

        // Use a post method.
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDARY);

        // Handle the other headers
        try {
            JSONObject headers = params.getJSONObject("headers");
            for (Iterator iter = headers.keys(); iter.hasNext();) {
                String headerKey = iter.next().toString();
                conn.setRequestProperty(headerKey, headers.getString(headerKey));
            }
        } catch (JSONException e1) {
            // No headers to be manipulated!
        }

        // Set the cookies on the response
        String cookie = CookieManager.getInstance().getCookie(target);
        if (cookie != null) {
            conn.setRequestProperty("Cookie", cookie);
        }

        /*
        * Store the non-file portions of the multipart data as a string, so that we can add it
        * to the contentSize, since it is part of the body of the HTTP request.
        */
        String extraParams = "";
        try {
            for (Iterator iter = params.keys(); iter.hasNext();) {
                Object key = iter.next();
                if (!String.valueOf(key).equals("headers")) {
                    extraParams += LINE_START + BOUNDARY + LINE_END;
                    extraParams += "Content-Disposition: form-data; name=\"" + key.toString() + "\";";
                    extraParams += LINE_END + LINE_END;
                    extraParams += params.getString(key.toString());
                    extraParams += LINE_END;
                }
            }
        } catch (JSONException e) {
            Log.e(LOG_TAG, e.getMessage(), e);
        }

        extraParams += LINE_START + BOUNDARY + LINE_END;
        extraParams += "Content-Disposition: form-data; name=\"" + fileKey + "\";" + " filename=\"";

        String midParams = "\"" + LINE_END + "Content-Type: " + mimeType + LINE_END + LINE_END;
        String tailParams = LINE_END + LINE_START + BOUNDARY + LINE_START + LINE_END;

        // Should set this up as an option
        if (chunkedMode) {
            conn.setChunkedStreamingMode(maxBufferSize);
        } else {
            int stringLength = extraParams.getBytes("UTF-8").length + midParams.getBytes("UTF-8").length
                    + tailParams.getBytes("UTF-8").length + fileName.getBytes("UTF-8").length;
            Log.d(LOG_TAG, "String Length: " + stringLength);
            int fixedLength = (int) fileInputStream.getChannel().size() + stringLength;
            Log.d(LOG_TAG, "Content Length: " + fixedLength);
            conn.setFixedLengthStreamingMode(fixedLength);
        }

        dos = new DataOutputStream(conn.getOutputStream());
        dos.write(extraParams.getBytes("UTF-8"));
        //We don't want to chagne encoding, we just want this to write for all Unicode.
        dos.write(fileName.getBytes("UTF-8"));
        dos.write(midParams.getBytes("UTF-8"));

        // create a buffer of maximum size
        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];

        // read file and write it into form...
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        totalBytes = 0;

        while (bytesRead > 0) {
            totalBytes += bytesRead;
            result.setBytesSent(totalBytes);
            dos.write(buffer, 0, bufferSize);
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        }

        // send multipart form data necesssary after file data...
        dos.write(tailParams.getBytes("UTF-8"));

        // close streams
        fileInputStream.close();
        dos.flush();
        dos.close();

        //------------------ read the SERVER RESPONSE
        StringBuffer responseString = new StringBuffer("");
        DataInputStream inStream;
        try {
            inStream = new DataInputStream(conn.getInputStream());
        } catch (FileNotFoundException e) {
            Log.e(LOG_TAG, e.toString(), e);
            throw new IOException("Received error from server");
        }

        String line;
        while ((line = inStream.readLine()) != null) {
            responseString.append(line);
        }
        Log.d(LOG_TAG, "got response from server");
        Log.d(LOG_TAG, responseString.toString());

        // send request and retrieve response
        result.setResponseCode(conn.getResponseCode());
        result.setResponse(responseString.toString());

        inStream.close();

        // Revert back to the proper verifier and socket factories
        if (trustEveryone && url.getProtocol().toLowerCase().equals("https")) {
            ((HttpsURLConnection) conn).setHostnameVerifier(defaultHostnameVerifier);
            HttpsURLConnection.setDefaultSSLSocketFactory(defaultSSLSocketFactory);
        }

        Log.d(LOG_TAG, "****** About to return a result from upload");
        return new PluginResult(PluginResult.Status.OK, result.toJSONObject());

    } catch (FileNotFoundException e) {
        JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source, target, conn);
        Log.e(LOG_TAG, error.toString(), e);
        return new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
    } catch (MalformedURLException e) {
        JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, conn);
        Log.e(LOG_TAG, error.toString(), e);
        return new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
    } catch (IOException e) {
        JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn);
        Log.e(LOG_TAG, error.toString(), e);
        return new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
    } catch (Throwable t) {
        // Shouldn't happen, but will
        JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn);
        Log.wtf(LOG_TAG, error.toString(), t);
        return new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}