Example usage for javax.net.ssl HttpsURLConnection setRequestProperty

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

Introduction

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

Prototype

public void setRequestProperty(String key, String value) 

Source Link

Document

Sets the general request property.

Usage

From source file:se.leap.bitmaskclient.ProviderAPI.java

/**
 * Executes an HTTP request expecting a JSON response.
 *
 * @param url/*from w w  w .  j a  v a  2  s  .  c om*/
 * @param request_method
 * @param parameters
 * @return response from authentication server
 */
private JSONObject sendToServer(String url, String request_method, Map<String, String> parameters) {
    JSONObject json_response;
    HttpsURLConnection urlConnection = null;
    try {
        InputStream is = null;
        urlConnection = (HttpsURLConnection) new URL(url).openConnection();
        urlConnection.setRequestMethod(request_method);
        String locale = Locale.getDefault().getLanguage() + Locale.getDefault().getCountry();
        urlConnection.setRequestProperty("Accept-Language", locale);
        urlConnection.setChunkedStreamingMode(0);
        urlConnection.setSSLSocketFactory(getProviderSSLSocketFactory());

        DataOutputStream writer = new DataOutputStream(urlConnection.getOutputStream());
        writer.writeBytes(formatHttpParameters(parameters));
        writer.close();

        is = urlConnection.getInputStream();
        String plain_response = new Scanner(is).useDelimiter("\\A").next();
        json_response = new JSONObject(plain_response);
    } catch (ClientProtocolException e) {
        json_response = getErrorMessage(urlConnection);
        e.printStackTrace();
    } catch (IOException e) {
        json_response = getErrorMessage(urlConnection);
        e.printStackTrace();
    } catch (JSONException e) {
        json_response = getErrorMessage(urlConnection);
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        json_response = getErrorMessage(urlConnection);
        e.printStackTrace();
    } catch (KeyManagementException e) {
        json_response = getErrorMessage(urlConnection);
        e.printStackTrace();
    } catch (KeyStoreException e) {
        json_response = getErrorMessage(urlConnection);
        e.printStackTrace();
    } catch (CertificateException e) {
        json_response = getErrorMessage(urlConnection);
        e.printStackTrace();
    }

    return json_response;
}

From source file:com.gmt2001.TwitchAPIv3.java

@SuppressWarnings("UseSpecificCatch")
private JSONObject GetData(request_type type, String url, String post, String oauth, boolean isJson) {
    JSONObject j = new JSONObject("{}");
    InputStream i = null;/* ww  w  .j  ava2  s . c om*/
    String rawcontent = "";

    try {
        if (url.contains("?")) {
            url += "&utcnow=" + System.currentTimeMillis();
        } else {
            url += "?utcnow=" + System.currentTimeMillis();
        }

        URL u = new URL(url);
        HttpsURLConnection c = (HttpsURLConnection) u.openConnection();

        c.addRequestProperty("Accept", header_accept);

        if (isJson) {
            c.addRequestProperty("Content-Type", "application/json");
        } else {
            c.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        }

        if (!clientid.isEmpty()) {
            c.addRequestProperty("Client-ID", clientid);
        }

        if (!oauth.isEmpty()) {
            c.addRequestProperty("Authorization", "OAuth " + oauth);
        }

        c.setRequestMethod(type.name());

        c.setUseCaches(false);
        c.setDefaultUseCaches(false);
        c.setConnectTimeout(timeout);
        c.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.52 Safari/537.36 PhantomBotJ/2015");

        if (!post.isEmpty()) {
            c.setDoOutput(true);
        }

        c.connect();

        if (!post.isEmpty()) {
            try (OutputStream o = c.getOutputStream()) {
                IOUtils.write(post, o);
            }
        }

        String content;

        if (c.getResponseCode() == 200) {
            i = c.getInputStream();
        } else {
            i = c.getErrorStream();
        }

        if (c.getResponseCode() == 204 || i == null) {
            content = "{}";
        } else {
            content = IOUtils.toString(i, c.getContentEncoding());
        }

        rawcontent = content;

        j = new JSONObject(content);
        j.put("_success", true);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", c.getResponseCode());
        j.put("_exception", "");
        j.put("_exceptionMessage", "");
        j.put("_content", content);
    } catch (JSONException ex) {
        if (ex.getMessage().contains("A JSONObject text must begin with")) {
            j = new JSONObject("{}");
            j.put("_success", true);
            j.put("_type", type.name());
            j.put("_url", url);
            j.put("_post", post);
            j.put("_http", 0);
            j.put("_exception", "");
            j.put("_exceptionMessage", "");
            j.put("_content", rawcontent);
        } else {
            com.gmt2001.Console.err.logStackTrace(ex);
        }
    } catch (NullPointerException ex) {
        com.gmt2001.Console.err.printStackTrace(ex);
    } catch (MalformedURLException ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_exception", "MalformedURLException");
        j.put("_exceptionMessage", ex.getMessage());
        j.put("_content", "");
        com.gmt2001.Console.err.logStackTrace(ex);
    } catch (SocketTimeoutException ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_exception", "SocketTimeoutException");
        j.put("_exceptionMessage", ex.getMessage());
        j.put("_content", "");
        com.gmt2001.Console.err.logStackTrace(ex);
    } catch (IOException ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_exception", "IOException");
        j.put("_exceptionMessage", ex.getMessage());
        j.put("_content", "");
        com.gmt2001.Console.err.logStackTrace(ex);
    } catch (Exception ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_exception", "Exception [" + ex.getClass().getName() + "]");
        j.put("_exceptionMessage", ex.getMessage());
        j.put("_content", "");
        com.gmt2001.Console.err.logStackTrace(ex);
    }

    if (i != null) {
        try {
            i.close();
        } catch (IOException ex) {
            j.put("_success", false);
            j.put("_type", type.name());
            j.put("_url", url);
            j.put("_post", post);
            j.put("_http", 0);
            j.put("_exception", "IOException");
            j.put("_exceptionMessage", ex.getMessage());
            j.put("_content", "");
            com.gmt2001.Console.err.logStackTrace(ex);
        }
    }

    return j;
}

From source file:com.flipzu.flipzu.FlipInterface.java

String postViaHttpsConnection(String path, String params) throws IOException {
    HttpsURLConnection c = null;
    InputStream is = null;//www .ja v  a  2  s  .  c  om
    OutputStream os = null;
    String respString = null;
    int rc;

    // String url = WSServerSecure + path;
    URL url = new URL(WSServerSecure + path);

    try {
        trustAllHosts();
        c = (HttpsURLConnection) url.openConnection();
        c.setHostnameVerifier(DO_NOT_VERIFY);

        c.setDoOutput(true);
        // Set the request method and headers
        c.setRequestMethod("POST");
        c.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.0");
        c.setRequestProperty("Content-Language", "en-US");
        c.setRequestProperty("Accept-Encoding", "identity");

        // Getting the output stream may flush the headers
        os = c.getOutputStream();
        os.write(params.getBytes());
        os.flush();

        // Getting the response code will open the connection,
        // send the request, and read the HTTP response headers.
        // The headers are stored until requested.
        rc = c.getResponseCode();
        if (rc != HttpURLConnection.HTTP_OK) {
            throw new IOException("HTTP response code: " + rc);
        }

        is = c.getInputStream();

        // Get the length and process the data
        int len = (int) c.getContentLength();
        if (len > 0) {
            int actual = 0;
            int bytesread = 0;
            byte[] data = new byte[len];
            while ((bytesread != len) && (actual != -1)) {
                actual = is.read(data, bytesread, len - bytesread);
                bytesread += actual;
            }
            respString = new String(data);

        } else {
            byte[] data = new byte[8192];
            int ch;
            int i = 0;
            while ((ch = is.read()) != -1) {
                if (i < data.length)
                    data[i] = ((byte) ch);
                i++;
            }
            respString = new String(data);
        }

    } catch (ClassCastException e) {
        debug.logW(TAG, "Not an HTTP URL");
        throw new IllegalArgumentException("Not an HTTP URL");
    } finally {
        if (is != null)
            is.close();
        if (os != null)
            os.close();
        if (c != null)
            c.disconnect();
    }

    return respString;
}

From source file:com.carvoyant.modularinput.Program.java

private JSONObject getRefreshToken(EventWriter ew, String clientId, String clientSecret, String refreshToken) {
    JSONObject tokenJson = null;// ww w  . java  2s.  com
    HttpsURLConnection getTokenConnection = null;

    try {
        BufferedReader tokenResponseReader = null;
        URL url = new URL("https://api.carvoyant.com/oauth/token");
        //         URL url = new URL("https://sandbox-api.carvoyant.com/sandbox/oauth/token");
        getTokenConnection = (HttpsURLConnection) url.openConnection();
        getTokenConnection.setReadTimeout(30000);
        getTokenConnection.setConnectTimeout(30000);
        getTokenConnection.setRequestMethod("POST");
        getTokenConnection.setDoInput(true);
        getTokenConnection.setDoOutput(true);

        List<SimpleEntry> getTokenParams = new ArrayList<SimpleEntry>();
        getTokenParams.add(new SimpleEntry("client_id", clientId));
        getTokenParams.add(new SimpleEntry("client_secret", clientSecret));
        getTokenParams.add(new SimpleEntry("grant_type", "refresh_token"));
        getTokenParams.add(new SimpleEntry("refresh_token", refreshToken));

        String userpass = clientId + ":" + clientSecret;
        String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes());

        getTokenConnection.setRequestProperty("Authorization", basicAuth);

        OutputStream os = getTokenConnection.getOutputStream();
        os.write(getQuery(getTokenParams).getBytes("UTF-8"));
        os.close();

        if (getTokenConnection.getResponseCode() < 400) {
            tokenResponseReader = new BufferedReader(
                    new InputStreamReader(getTokenConnection.getInputStream()));
            String inputLine;
            StringBuffer sb = new StringBuffer();
            while ((inputLine = tokenResponseReader.readLine()) != null) {
                sb.append(inputLine);
            }

            tokenJson = new JSONObject(sb.toString());
            ew.synchronizedLog(EventWriter.INFO, "Refreshed Carvoyant access token.");
        } else {
            tokenResponseReader = new BufferedReader(
                    new InputStreamReader(getTokenConnection.getErrorStream()));
            StringBuffer sb = new StringBuffer();
            String inputLine;
            while ((inputLine = tokenResponseReader.readLine()) != null) {
                sb.append(inputLine);
            }
            ew.synchronizedLog(EventWriter.ERROR, "Carvoyant Refresh Token Error. CLIENT_ID:" + clientId
                    + ", REFRESH_TOKEN:" + refreshToken + ",ERROR_MSG: " + sb.toString());
        }

        getTokenConnection.disconnect();
    } catch (MalformedURLException mue) {
        ew.synchronizedLog(EventWriter.ERROR, "Carvoyant Refresh Token Error: " + mue.getMessage());
    } catch (IOException ioe) {
        ew.synchronizedLog(EventWriter.ERROR, "Carvoyant Refresh Token Error: " + ioe.getMessage());
    } finally {
        if (null != getTokenConnection) {
            getTokenConnection.disconnect();
        }
    }

    return tokenJson;
}

From source file:eu.faircode.netguard.ServiceJob.java

@Override
public boolean onStartJob(JobParameters params) {
    Log.i(TAG, "Start job=" + params.getJobId());

    new AsyncTask<JobParameters, Object, Object>() {

        @Override/*from   w w w  .  ja va  2  s. c om*/
        protected JobParameters doInBackground(JobParameters... params) {
            Log.i(TAG, "Executing job=" + params[0].getJobId());

            HttpsURLConnection urlConnection = null;
            try {
                String android_id = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
                JSONObject json = new JSONObject();

                json.put("device", Util.sha256(android_id, ""));
                json.put("product", Build.DEVICE);
                json.put("sdk", Build.VERSION.SDK_INT);
                json.put("country", Locale.getDefault().getCountry());

                json.put("netguard", Util.getSelfVersionCode(ServiceJob.this));
                try {
                    json.put("store", getPackageManager().getInstallerPackageName(getPackageName()));
                } catch (Throwable ex) {
                    Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                    json.put("store", null);
                }

                for (String name : params[0].getExtras().keySet())
                    json.put(name, params[0].getExtras().get(name));

                urlConnection = (HttpsURLConnection) new URL(cUrl).openConnection();
                urlConnection.setConnectTimeout(cTimeOutMs);
                urlConnection.setReadTimeout(cTimeOutMs);
                urlConnection.setRequestProperty("Accept", "application/json");
                urlConnection.setRequestProperty("Content-type", "application/json");
                urlConnection.setRequestMethod("POST");
                urlConnection.setDoInput(true);
                urlConnection.setDoOutput(true);

                OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
                out.write(json.toString().getBytes()); // UTF-8
                out.flush();

                int code = urlConnection.getResponseCode();
                if (code != HttpsURLConnection.HTTP_OK)
                    throw new IOException("HTTP " + code);

                InputStreamReader isr = new InputStreamReader(urlConnection.getInputStream());
                Log.i(TAG, "Response=" + Util.readString(isr).toString());

                jobFinished(params[0], false);

                if ("rule".equals(params[0].getExtras().getString("type"))) {
                    SharedPreferences history = getSharedPreferences("history", Context.MODE_PRIVATE);
                    history.edit().putLong(params[0].getExtras().getString("package") + ":submitted",
                            new Date().getTime()).apply();
                }

            } catch (Throwable ex) {
                Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                jobFinished(params[0], true);

            } finally {
                if (urlConnection != null)
                    urlConnection.disconnect();

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ignored) {
                }
            }

            return null;
        }
    }.execute(params);

    return true;
}

From source file:com.gmt2001.TwitchAPIv5.java

@SuppressWarnings("UseSpecificCatch")
private JSONObject GetData(request_type type, String url, String post, String oauth, boolean isJson) {
    JSONObject j = new JSONObject("{}");
    InputStream i = null;/*from   www.  jav a2s .co m*/
    String content = "";

    try {
        URL u = new URL(url);
        HttpsURLConnection c = (HttpsURLConnection) u.openConnection();
        c.addRequestProperty("Accept", header_accept);
        c.addRequestProperty("Content-Type", isJson ? "application/json" : "application/x-www-form-urlencoded");

        if (!clientid.isEmpty()) {
            c.addRequestProperty("Client-ID", clientid);
        }

        if (!oauth.isEmpty()) {
            c.addRequestProperty("Authorization", "OAuth " + oauth);
        } else {
            if (!this.oauth.isEmpty()) {
                c.addRequestProperty("Authorization", "OAuth " + oauth);
            }
        }

        c.setRequestMethod(type.name());
        c.setConnectTimeout(timeout);
        c.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.52 Safari/537.36 PhantomBotJ/2015");

        if (!post.isEmpty()) {
            c.setDoOutput(true);
        }

        c.connect();

        if (!post.isEmpty()) {
            try (OutputStream o = c.getOutputStream()) {
                IOUtils.write(post, o);
            }
        }

        if (c.getResponseCode() == 200) {
            i = c.getInputStream();
        } else {
            i = c.getErrorStream();
        }

        if (c.getResponseCode() == 204 || i == null) {
            content = "{}";
        } else {
            // default to UTF-8, it'll probably be the best bet if there's
            // no charset specified.
            String charset = "utf-8";
            String ct = c.getContentType();
            if (ct != null) {
                String[] cts = ct.split(" *; *");
                for (int idx = 1; idx < cts.length; ++idx) {
                    String[] val = cts[idx].split("=", 2);
                    if (val[0] == "charset" && val.length > 1) {
                        charset = val[1];
                    }
                }
            }

            if ("gzip".equals(c.getContentEncoding())) {
                i = new GZIPInputStream(i);
            }

            content = IOUtils.toString(i, charset);
        }

        j = new JSONObject(content);
        fillJSONObject(j, true, type.name(), post, url, c.getResponseCode(), "", "", content);
    } catch (Exception ex) {
        Throwable rootCause = ex;
        while (rootCause.getCause() != null && rootCause.getCause() != rootCause) {
            rootCause = rootCause.getCause();
        }

        fillJSONObject(j, false, type.name(), post, url, 0, ex.getClass().getSimpleName(), ex.getMessage(),
                content);
        com.gmt2001.Console.debug
                .println("Failed to get data [" + ex.getClass().getSimpleName() + "]: " + ex.getMessage());
    } finally {
        if (i != null) {
            try {
                i.close();
            } catch (IOException ex) {
                fillJSONObject(j, false, type.name(), post, url, 0, "IOException", ex.getMessage(), content);
                com.gmt2001.Console.err.println("IOException: " + ex.getMessage());
            }
        }
    }

    return j;
}

From source file:com.citrus.mobile.RESTclient.java

public JSONObject makeSendMoneyRequest(String accessToken, CitrusUser toUser, Amount amount, String message) {
    HttpsURLConnection conn;
    DataOutputStream wr = null;//from ww w.j a va  2s. co m
    JSONObject txnDetails = null;
    BufferedReader in = null;

    try {
        String url = null;

        StringBuffer postDataBuff = new StringBuffer("amount=");
        postDataBuff.append(amount.getValue());

        postDataBuff.append("&currency=");
        postDataBuff.append(amount.getCurrency());

        postDataBuff.append("&message=");
        postDataBuff.append(message);

        if (!TextUtils.isEmpty(toUser.getEmailId())) {
            url = urls.getString(base_url) + urls.getString("transfer");
            postDataBuff.append("&to=");
            postDataBuff.append(toUser.getEmailId());

        } else if (!TextUtils.isEmpty(toUser.getMobileNo())) {
            url = urls.getString(base_url) + urls.getString("suspensetransfer");

            postDataBuff.append("&to=");
            postDataBuff.append(toUser.getMobileNo());

        }

        conn = (HttpsURLConnection) new URL(url).openConnection();

        //add reuqest header
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Authorization", "Bearer " + accessToken);

        conn.setDoOutput(true);
        wr = new DataOutputStream(conn.getOutputStream());

        wr.writeBytes(postDataBuff.toString());
        wr.flush();

        int responseCode = conn.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + postDataBuff.toString());
        System.out.println("Response Code : " + responseCode);

        in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }

        txnDetails = new JSONObject(response.toString());

    } catch (JSONException exception) {
        exception.printStackTrace();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        try {
            if (wr != null) {
                wr.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return txnDetails;
}

From source file:io.teak.sdk.Session.java

private void startHeartbeat() {
    final Session _this = this;

    this.heartbeatService = Executors.newSingleThreadScheduledExecutor();
    this.heartbeatService.scheduleAtFixedRate(new Runnable() {
        public void run() {
            if (Teak.isDebug) {
                Log.v(LOG_TAG, "Sending heartbeat for user: " + userId);
            }/*from  w ww  .  j  av  a 2s  .  c  om*/

            HttpsURLConnection connection = null;
            try {
                String queryString = "game_id=" + URLEncoder.encode(_this.appConfiguration.appId, "UTF-8")
                        + "&api_key=" + URLEncoder.encode(_this.userId, "UTF-8") + "&sdk_version="
                        + URLEncoder.encode(Teak.SDKVersion, "UTF-8") + "&sdk_platform="
                        + URLEncoder.encode(_this.deviceConfiguration.platformString, "UTF-8") + "&app_version="
                        + URLEncoder.encode(String.valueOf(_this.appConfiguration.appVersion), "UTF-8")
                        + (_this.countryCode == null ? ""
                                : "&country_code="
                                        + URLEncoder.encode(String.valueOf(_this.countryCode), "UTF-8"))
                        + "&buster=" + URLEncoder.encode(UUID.randomUUID().toString(), "UTF-8");
                URL url = new URL("https://iroko.gocarrot.com/ping?" + queryString);
                connection = (HttpsURLConnection) url.openConnection();
                connection.setRequestProperty("Accept-Charset", "UTF-8");
                connection.setUseCaches(false);

                int responseCode = connection.getResponseCode();
                if (Teak.isDebug) {
                    Log.v(LOG_TAG, "Heartbeat response code: " + responseCode);
                }
            } catch (Exception e) {
                Log.e(LOG_TAG, Log.getStackTraceString(e));
            } finally {
                if (connection != null) {
                    connection.disconnect();
                }
            }
        }
    }, 0, 1, TimeUnit.MINUTES); // TODO: If RemoteConfiguration specifies a different rate, use that
}

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;// w  ww . j a va  2s  .  co m
    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");
}

From source file:org.kuali.mobility.push.dao.PushDaoImpl.java

@SuppressWarnings("unchecked")
private boolean sendPushToAndroid(Push push, Device device) {

    try {/*from  w w  w  .  j a va  2s. c  om*/
        HttpsURLConnection.setDefaultHostnameVerifier(new CustomizedHostnameVerifier());
        URL url = new URL("https://android.apis.google.com/c2dm/send");
        HttpsURLConnection request = (HttpsURLConnection) url.openConnection();

        LOG.info("---- Version: " + url.getClass().getPackage().getSpecificationVersion());
        LOG.info("---- Impl:    " + url.getClass().getPackage().getImplementationVersion());
        String handlers = System.getProperty("java.protocol.handler.pkgs");

        LOG.info(handlers);
        request.setDoOutput(true);
        request.setDoInput(true);

        StringBuilder buf = new StringBuilder();
        buf.append("registration_id").append("=").append((URLEncoder.encode(device.getRegId(), "UTF-8")));
        buf.append("&collapse_key").append("=")
                .append((URLEncoder.encode(push.getPostedTimestamp().toString(), "UTF-8")));
        buf.append("&data.message").append("=").append((URLEncoder.encode(push.getMessage(), "UTF-8")));
        buf.append("&data.title").append("=").append((URLEncoder.encode(push.getTitle(), "UTF-8")));
        buf.append("&data.id").append("=").append((URLEncoder.encode(push.getPushId().toString(), "UTF-8")));
        buf.append("&data.url").append("=").append((URLEncoder.encode(push.getUrl().toString(), "UTF-8")));

        String emer = (push.getEmergency()) ? "YES" : "NO";
        buf.append("&data.emer").append("=").append((URLEncoder.encode(emer, "UTF-8")));

        request.setRequestMethod("POST");
        request.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        request.setRequestProperty("Content-Length", buf.toString().getBytes().length + "");
        request.setRequestProperty("Authorization", "GoogleLogin auth=" + GoogleAuthToken);

        LOG.info("SEND Android Buffer: " + buf.toString());

        OutputStreamWriter post = new OutputStreamWriter(request.getOutputStream());
        post.write(buf.toString());
        post.flush();

        BufferedReader in = new BufferedReader(new InputStreamReader(request.getInputStream()));
        buf = new StringBuilder();
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            buf.append(inputLine);
        }
        post.close();
        in.close();

        LOG.info("response from C2DM server:\n" + buf.toString());

    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return false;
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return false;
    }
    return true;
}