Example usage for javax.net.ssl HttpsURLConnection setFixedLengthStreamingMode

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

Introduction

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

Prototype

public void setFixedLengthStreamingMode(int contentLength) 

Source Link

Document

This method is used to enable streaming of a HTTP request body without internal buffering, when the content length is known in advance.

Usage

From source file:org.kuali.mobility.push.service.send.AndroidSendService.java

/**
 * Writes the data over the connection/*from   w ww.j a va  2s . co m*/
 * @param conn
 * @param data
 * @return
 * @throws java.net.MalformedURLException
 * @throws java.io.IOException
 */
private static String sendToGCM(HttpsURLConnection conn, String data) throws IOException {
    byte[] dataBytes = data.getBytes();
    conn.setFixedLengthStreamingMode(dataBytes.length);
    OutputStream out = null;
    String response = null;
    try {
        out = conn.getOutputStream();
        out.write(dataBytes);
        out.flush();
        response = readResponse(conn);

    } catch (IOException e) {
        LOG.warn("Exception while trying to write data to GCM", e);
    } finally {
        IOUtils.closeQuietly(out);
        conn.disconnect();
    }
    return response;
}

From source file:no.digipost.android.api.ApiAccess.java

public static void uploadFile(Context context, String uri, File file) throws DigipostClientException {
    try {//ww w .ja v a 2 s  .c om
        try {

            FileBody filebody = new FileBody(file, ApiConstants.CONTENT_OCTET_STREAM);
            MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null,
                    Charset.forName(ApiConstants.ENCODING));
            multipartEntity.addPart("subject", new StringBody(FilenameUtils.removeExtension(file.getName()),
                    ApiConstants.MIME, Charset.forName(ApiConstants.ENCODING)));
            multipartEntity.addPart("file", filebody);
            multipartEntity.addPart("token", new StringBody(TokenStore.getAccess()));

            URL url = new URL(uri);
            HttpsURLConnection httpsClient = (HttpsURLConnection) url.openConnection();
            httpsClient.setRequestMethod("POST");
            httpsClient.setDoOutput(true);
            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                httpsClient.setFixedLengthStreamingMode(multipartEntity.getContentLength());
            } else {
                httpsClient.setChunkedStreamingMode(0);
            }
            httpsClient.setRequestProperty("Connection", "Keep-Alive");
            httpsClient.addRequestProperty("Content-length", multipartEntity.getContentLength() + "");
            httpsClient.setRequestProperty(ApiConstants.AUTHORIZATION,
                    ApiConstants.BEARER + TokenStore.getAccess());
            httpsClient.addRequestProperty(multipartEntity.getContentType().getName(),
                    multipartEntity.getContentType().getValue());

            try {
                OutputStream outputStream = new BufferedOutputStream(httpsClient.getOutputStream());
                multipartEntity.writeTo(outputStream);
                outputStream.flush();
                NetworkUtilities.checkHttpStatusCode(context, httpsClient.getResponseCode());
            } finally {
                httpsClient.disconnect();
            }

        } catch (DigipostInvalidTokenException e) {
            OAuth.updateAccessTokenWithRefreshToken(context);
            uploadFile(context, uri, file);
        }
    } catch (Exception e) {
        e.printStackTrace();
        Log.e(TAG, context.getString(R.string.error_your_network));
        throw new DigipostClientException(context.getString(R.string.error_your_network));
    }
}

From source file:in.rab.ordboken.NeClient.java

private void loginMainSite() throws IOException, LoginException {
    ArrayList<BasicNameValuePair> data = new ArrayList<BasicNameValuePair>();

    data.add(new BasicNameValuePair("_save_loginForm", "true"));
    data.add(new BasicNameValuePair("redir", "/success"));
    data.add(new BasicNameValuePair("redirFail", "/fail"));
    data.add(new BasicNameValuePair("userName", mUsername));
    data.add(new BasicNameValuePair("passWord", mPassword));

    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(data);

    URL url = new URL("https://www.ne.se/user/login.jsp");
    HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
    https.setInstanceFollowRedirects(false);
    https.setFixedLengthStreamingMode((int) entity.getContentLength());
    https.setDoOutput(true);/*w  w  w. j  a  v  a2  s .  c  om*/

    try {
        OutputStream output = https.getOutputStream();
        entity.writeTo(output);
        output.close();

        Integer response = https.getResponseCode();
        if (response != 302) {
            throw new LoginException("Unexpected response: " + response);
        }

        String location = https.getHeaderField("Location");
        if (!location.contains("/success")) {
            throw new LoginException("Failed to login");
        }
    } finally {
        https.disconnect();
    }
}

From source file:online.privacy.PrivacyOnlineApiRequest.java

private JSONObject makeAPIRequest(String method, String endPoint, String jsonPayload)
        throws IOException, JSONException {
    InputStream inputStream = null;
    OutputStream outputStream = null;
    String apiUrl = "https://api.privacy.online";
    String apiKey = this.context.getString(R.string.privacy_online_api_key);
    String keyString = "?key=" + apiKey;

    int payloadSize = jsonPayload.length();

    try {/*  w w w  .j a v  a  2s .com*/
        URL url = new URL(apiUrl + endPoint + keyString);
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();

        // Sec 5 second connect/read timeouts
        connection.setReadTimeout(5000);
        connection.setConnectTimeout(5000);
        connection.setRequestMethod(method);
        connection.setRequestProperty("Content-Type", "application/json");

        if (payloadSize > 0) {
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setFixedLengthStreamingMode(payloadSize);
        }

        // Initiate the connection
        connection.connect();

        // Write the payload if there is one.
        if (payloadSize > 0) {
            outputStream = connection.getOutputStream();
            outputStream.write(jsonPayload.getBytes("UTF-8"));
        }

        // Get the response code ...
        int responseCode = connection.getResponseCode();
        Log.e(LOG_TAG, "Response code: " + responseCode);

        switch (responseCode) {
        case HttpsURLConnection.HTTP_OK:
            inputStream = connection.getInputStream();
            break;
        case HttpsURLConnection.HTTP_FORBIDDEN:
            inputStream = connection.getErrorStream();
            break;
        case HttpURLConnection.HTTP_NOT_FOUND:
            inputStream = connection.getErrorStream();
            break;
        case HttpsURLConnection.HTTP_UNAUTHORIZED:
            inputStream = connection.getErrorStream();
            break;
        default:
            inputStream = connection.getInputStream();
            break;
        }

        String responseContent = "{}"; // Default to an empty object.
        if (inputStream != null) {
            responseContent = readInputStream(inputStream, connection.getContentLength());
        }

        JSONObject responseObject = new JSONObject(responseContent);
        responseObject.put("code", responseCode);

        return responseObject;

    } finally {
        if (inputStream != null) {
            inputStream.close();
        }
        if (outputStream != null) {
            outputStream.close();
        }
    }
}

From source file:org.whispersystems.signalservice.internal.push.PushServiceSocket.java

private void uploadAttachment(String method, String url, InputStream data, long dataSize, byte[] key,
        ProgressListener listener) throws IOException {
    URL uploadUrl = new URL(url);
    HttpsURLConnection connection = (HttpsURLConnection) uploadUrl.openConnection();
    connection.setDoOutput(true);//  www .j  av a 2  s . c  om

    if (dataSize > 0) {
        connection
                .setFixedLengthStreamingMode((int) AttachmentCipherOutputStream.getCiphertextLength(dataSize));
    } else {
        connection.setChunkedStreamingMode(0);
    }

    connection.setRequestMethod(method);
    connection.setRequestProperty("Content-Type", "application/octet-stream");
    connection.setRequestProperty("Connection", "close");
    connection.connect();

    try {
        OutputStream stream = connection.getOutputStream();
        AttachmentCipherOutputStream out = new AttachmentCipherOutputStream(key, stream);
        byte[] buffer = new byte[4096];
        int read, written = 0;

        while ((read = data.read(buffer)) != -1) {
            out.write(buffer, 0, read);
            written += read;

            if (listener != null) {
                listener.onAttachmentProgress(dataSize, written);
            }
        }

        data.close();
        out.flush();
        out.close();

        if (connection.getResponseCode() != 200) {
            throw new IOException(
                    "Bad response: " + connection.getResponseCode() + " " + connection.getResponseMessage());
        }
    } finally {
        connection.disconnect();
    }
}

From source file:org.appspot.apprtc.util.AsyncHttpURLConnection.java

private void sendHttpMessage() {
    if (mIsBitmap) {
        Bitmap bitmap = ThumbnailsCacheManager.getBitmapFromDiskCache(url);

        if (bitmap != null) {
            events.onHttpComplete(bitmap);
            return;
        }//www  .  ja  v a2s .  c o  m
    }

    X509TrustManager trustManager = new X509TrustManager() {

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            // NOTE : This is where we can calculate the certificate's fingerprint,
            // show it to the user and throw an exception in case he doesn't like it
        }

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }
    };

    //HttpsURLConnection.setDefaultHostnameVerifier(new NullHostNameVerifier());
    // Create a trust manager that does not validate certificate chains
    X509TrustManager[] trustAllCerts = new X509TrustManager[] { trustManager };

    // Install the all-trusting trust manager
    SSLSocketFactory noSSLv3Factory = null;
    try {
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
            noSSLv3Factory = new TLSSocketFactory(trustAllCerts, new SecureRandom());
        } else {
            noSSLv3Factory = sc.getSocketFactory();
        }
        HttpsURLConnection.setDefaultSSLSocketFactory(noSSLv3Factory);
    } catch (GeneralSecurityException e) {
    }

    HttpsURLConnection connection = null;
    try {
        URL urlObj = new URL(url);
        connection = (HttpsURLConnection) urlObj.openConnection();
        connection.setSSLSocketFactory(noSSLv3Factory);

        HttpsURLConnection.setDefaultHostnameVerifier(new NullHostNameVerifier(urlObj.getHost()));
        connection.setHostnameVerifier(new NullHostNameVerifier(urlObj.getHost()));
        byte[] postData = new byte[0];
        if (message != null) {
            postData = message.getBytes("UTF-8");
        }

        if (msCookieManager.getCookieStore().getCookies().size() > 0) {
            // While joining the Cookies, use ',' or ';' as needed. Most of the servers are using ';'
            connection.setRequestProperty("Cookie",
                    TextUtils.join(";", msCookieManager.getCookieStore().getCookies()));
        }

        /*if (method.equals("PATCH")) {
          connection.setRequestProperty("X-HTTP-Method-Override", "PATCH");
          connection.setRequestMethod("POST");
        }
        else {*/
        connection.setRequestMethod(method);
        //}

        if (authorization.length() != 0) {
            connection.setRequestProperty("Authorization", authorization);
        }
        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setConnectTimeout(HTTP_TIMEOUT_MS);
        connection.setReadTimeout(HTTP_TIMEOUT_MS);
        // TODO(glaznev) - query request origin from pref_room_server_url_key preferences.
        //connection.addRequestProperty("origin", HTTP_ORIGIN);
        boolean doOutput = false;
        if (method.equals("POST") || method.equals("PATCH")) {
            doOutput = true;
            connection.setDoOutput(true);
            connection.setFixedLengthStreamingMode(postData.length);
        }
        if (contentType == null) {
            connection.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
        } else {
            connection.setRequestProperty("Content-Type", contentType);
        }

        // Send POST request.
        if (doOutput && postData.length > 0) {
            OutputStream outStream = connection.getOutputStream();
            outStream.write(postData);
            outStream.close();
        }

        // Get response.
        int responseCode = 200;
        try {
            connection.getResponseCode();
        } catch (IOException e) {

        }
        getCookies(connection);
        InputStream responseStream;

        if (responseCode > 400) {
            responseStream = connection.getErrorStream();
        } else {
            responseStream = connection.getInputStream();
        }

        String responseType = connection.getContentType();
        if (responseType.startsWith("image/")) {
            Bitmap bitmap = BitmapFactory.decodeStream(responseStream);
            if (mIsBitmap && bitmap != null) {
                ThumbnailsCacheManager.addBitmapToCache(url, bitmap);
            }
            events.onHttpComplete(bitmap);
        } else {
            String response = drainStream(responseStream);
            events.onHttpComplete(response);
        }
        responseStream.close();
        connection.disconnect();
    } catch (SocketTimeoutException e) {
        events.onHttpError("HTTP " + method + " to " + url + " timeout");
    } catch (IOException e) {
        if (connection != null) {
            connection.disconnect();
        }
        events.onHttpError("HTTP " + method + " to " + url + " error: " + e.getMessage());
    } catch (ClassCastException e) {
        e.printStackTrace();
    }
}

From source file:org.openhab.binding.amazonechocontrol.internal.Connection.java

public HttpsURLConnection makeRequest(String verb, String url, @Nullable String postData, boolean json,
        boolean autoredirect, @Nullable Map<String, String> customHeaders)
        throws IOException, URISyntaxException {
    String currentUrl = url;//from ww w .j a  v  a2s. c  om
    for (int i = 0; i < 30; i++) // loop for handling redirect, using automatic redirect is not possible, because
                                 // all response headers must be catched
    {
        int code;
        HttpsURLConnection connection = null;
        try {
            logger.debug("Make request to {}", url);
            connection = (HttpsURLConnection) new URL(currentUrl).openConnection();
            connection.setRequestMethod(verb);
            connection.setRequestProperty("Accept-Language", "en-US");
            if (customHeaders == null || !customHeaders.containsKey("User-Agent")) {
                connection.setRequestProperty("User-Agent", userAgent);
            }
            connection.setRequestProperty("Accept-Encoding", "gzip");
            connection.setRequestProperty("DNT", "1");
            connection.setRequestProperty("Upgrade-Insecure-Requests", "1");
            if (customHeaders != null) {
                for (String key : customHeaders.keySet()) {
                    String value = customHeaders.get(key);
                    if (StringUtils.isNotEmpty(value)) {
                        connection.setRequestProperty(key, value);
                    }
                }
            }
            connection.setInstanceFollowRedirects(false);

            // add cookies
            URI uri = connection.getURL().toURI();

            if (customHeaders == null || !customHeaders.containsKey("Cookie")) {

                StringBuilder cookieHeaderBuilder = new StringBuilder();
                for (HttpCookie cookie : cookieManager.getCookieStore().get(uri)) {
                    if (cookieHeaderBuilder.length() > 0) {
                        cookieHeaderBuilder.append(";");
                    }
                    cookieHeaderBuilder.append(cookie.getName());
                    cookieHeaderBuilder.append("=");
                    cookieHeaderBuilder.append(cookie.getValue());
                    if (cookie.getName().equals("csrf")) {
                        connection.setRequestProperty("csrf", cookie.getValue());
                    }

                }
                if (cookieHeaderBuilder.length() > 0) {
                    String cookies = cookieHeaderBuilder.toString();
                    connection.setRequestProperty("Cookie", cookies);
                }
            }
            if (postData != null) {

                logger.debug("{}: {}", verb, postData);
                // post data
                byte[] postDataBytes = postData.getBytes(StandardCharsets.UTF_8);
                int postDataLength = postDataBytes.length;

                connection.setFixedLengthStreamingMode(postDataLength);

                if (json) {
                    connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
                } else {
                    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                }
                connection.setRequestProperty("Content-Length", Integer.toString(postDataLength));
                if (verb == "POST") {
                    connection.setRequestProperty("Expect", "100-continue");
                }

                connection.setDoOutput(true);
                OutputStream outputStream = connection.getOutputStream();
                outputStream.write(postDataBytes);
                outputStream.close();
            }
            // handle result
            code = connection.getResponseCode();
            String location = null;

            // handle response headers
            Map<String, List<String>> headerFields = connection.getHeaderFields();
            for (Map.Entry<String, List<String>> header : headerFields.entrySet()) {
                String key = header.getKey();
                if (StringUtils.isNotEmpty(key)) {
                    if (key.equalsIgnoreCase("Set-Cookie")) {
                        // store cookie
                        for (String cookieHeader : header.getValue()) {
                            if (StringUtils.isNotEmpty(cookieHeader)) {

                                List<HttpCookie> cookies = HttpCookie.parse(cookieHeader);
                                for (HttpCookie cookie : cookies) {
                                    cookieManager.getCookieStore().add(uri, cookie);
                                }
                            }
                        }
                    }
                    if (key.equalsIgnoreCase("Location")) {
                        // get redirect location
                        location = header.getValue().get(0);
                        if (StringUtils.isNotEmpty(location)) {
                            location = uri.resolve(location).toString();
                            // check for https
                            if (location.toLowerCase().startsWith("http://")) {
                                // always use https
                                location = "https://" + location.substring(7);
                                logger.debug("Redirect corrected to {}", location);
                            }
                        }
                    }
                }
            }
            if (code == 200) {
                logger.debug("Call to {} succeeded", url);
                return connection;
            }
            if (code == 302 && location != null) {
                logger.debug("Redirected to {}", location);
                currentUrl = location;
                if (autoredirect) {
                    continue;
                }
                return connection;
            }
        } catch (IOException e) {

            if (connection != null) {
                connection.disconnect();
            }
            logger.warn("Request to url '{}' fails with unkown error", url, e);
            throw e;
        } catch (Exception e) {
            if (connection != null) {
                connection.disconnect();
            }
            throw e;
        }
        if (code != 200) {
            throw new HttpException(code,
                    verb + " url '" + url + "' failed: " + connection.getResponseMessage());
        }
    }
    throw new ConnectionException("Too many redirects");
}