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:mediasearch.twitter.TwitterService.java

private HttpsURLConnection setUpConnection(String requestMethod, String endPointUrl, String authorization,
        String authValue) throws IOException {
    URL url = new URL(endPointUrl);
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
    connection.setDoOutput(true);/* w w w  .  j  a v a2s . c  o m*/
    connection.setDoInput(true);
    connection.setRequestMethod(requestMethod);
    connection.setRequestProperty("Host", "api.twitter.com");
    connection.setRequestProperty("User-Agent", "NewSeedCloud");
    connection.setRequestProperty("Authorization", authorization + authValue);
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
    //connection.setRequestProperty("Content-Length", "29");
    connection.setUseCaches(false);
    if (!authorization.contains("Bearer ")) {
        writeRequest(connection, "grant_type=client_credentials");
    }
    return connection;
}

From source file:com.microsoft.valda.oms.OmsAppender.java

private void sendLog(LoggingEvent event)
        throws NoSuchAlgorithmException, InvalidKeyException, IOException, HTTPException {
    //create JSON message
    JSONObject obj = new JSONObject();
    obj.put("LOGBACKLoggerName", event.getLoggerName());
    obj.put("LOGBACKLogLevel", event.getLevel().toString());
    obj.put("LOGBACKMessage", event.getFormattedMessage());
    obj.put("LOGBACKThread", event.getThreadName());
    if (event.getCallerData() != null && event.getCallerData().length > 0) {
        obj.put("LOGBACKCallerData", event.getCallerData()[0].toString());
    } else {/*from  ww  w.ja va 2  s.com*/
        obj.put("LOGBACKCallerData", "");
    }
    if (event.getThrowableProxy() != null) {
        obj.put("LOGBACKStackTrace", ThrowableProxyUtil.asString(event.getThrowableProxy()));
    } else {
        obj.put("LOGBACKStackTrace", "");
    }
    if (inetAddress != null) {
        obj.put("LOGBACKIPAddress", inetAddress.getHostAddress());
    } else {
        obj.put("LOGBACKIPAddress", "0.0.0.0");
    }
    String json = obj.toJSONString();

    String Signature = "";
    String encodedHash = "";
    String url = "";

    // Todays date input for OMS Log Analytics
    Calendar calendar = Calendar.getInstance();
    SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
    dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
    String timeNow = dateFormat.format(calendar.getTime());

    // String for signing the key
    String stringToSign = "POST\n" + json.length() + "\napplication/json\nx-ms-date:" + timeNow + "\n/api/logs";
    byte[] decodedBytes = Base64.decodeBase64(sharedKey);
    Mac hasher = Mac.getInstance("HmacSHA256");
    hasher.init(new SecretKeySpec(decodedBytes, "HmacSHA256"));
    byte[] hash = hasher.doFinal(stringToSign.getBytes());

    encodedHash = DatatypeConverter.printBase64Binary(hash);
    Signature = "SharedKey " + customerId + ":" + encodedHash;

    url = "https://" + customerId + ".ods.opinsights.azure.com/api/logs?api-version=2016-04-01";
    URL objUrl = new URL(url);
    HttpsURLConnection con = (HttpsURLConnection) objUrl.openConnection();
    con.setDoOutput(true);
    con.setRequestMethod("POST");
    con.setRequestProperty("Content-Type", "application/json");
    con.setRequestProperty("Log-Type", logType);
    con.setRequestProperty("x-ms-date", timeNow);
    con.setRequestProperty("Authorization", Signature);

    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(json);
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();
    if (responseCode != 200) {
        throw new HTTPException(responseCode);
    }
}

From source file:de.btobastian.javacord.entities.impl.ImplCustomEmoji.java

@Override
public Future<byte[]> getEmojiAsByteArray(FutureCallback<byte[]> callback) {
    ListenableFuture<byte[]> future = api.getThreadPool().getListeningExecutorService()
            .submit(new Callable<byte[]>() {
                @Override/*from ww w. ja  v a  2  s. c  om*/
                public byte[] call() throws Exception {
                    logger.debug("Trying to get emoji {} from server {}", ImplCustomEmoji.this, server);
                    URL url = getImageUrl();
                    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
                    conn.setRequestMethod("GET");
                    conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
                    conn.setRequestProperty("User-Agent", Javacord.USER_AGENT);
                    InputStream in = new BufferedInputStream(conn.getInputStream());
                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    byte[] buf = new byte[1024];
                    int n;
                    while (-1 != (n = in.read(buf))) {
                        out.write(buf, 0, n);
                    }
                    out.close();
                    in.close();
                    byte[] emoji = out.toByteArray();
                    logger.debug("Got emoji {} from server {} (size: {})", ImplCustomEmoji.this, server,
                            emoji.length);
                    return emoji;
                }
            });
    if (callback != null) {
        Futures.addCallback(future, callback);
    }
    return future;
}

From source file:org.wso2.carbon.integration.common.tests.JaggeryServerTest.java

/**
 * Sending the request and getting the response
 * @param Uri - request url/*  w  ww . j  a  va  2s  .  co  m*/
 * @param append - append request parameters
 * @throws IOException
 */
private HttpsResponse getRequest(String Uri, String requestParameters, boolean append) throws IOException {
    if (Uri.startsWith("https://")) {
        String urlStr = Uri;
        if (requestParameters != null && requestParameters.length() > 0) {
            if (append) {
                urlStr += "?" + requestParameters;
            } else {
                urlStr += requestParameters;
            }
        }
        URL url = new URL(urlStr);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setDoOutput(true);
        conn.setHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        conn.setReadTimeout(30000);
        conn.connect();
        // Get the response
        StringBuilder sb = new StringBuilder();
        BufferedReader rd = null;
        try {
            rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
        } catch (FileNotFoundException ignored) {
        } catch (IOException ignored) {
        } finally {
            if (rd != null) {
                rd.close();
            }
            conn.disconnect();
        }
        return new HttpsResponse(sb.toString(), conn.getResponseCode());
    }
    return null;
}

From source file:org.talend.components.marketo.runtime.client.MarketoBulkExecClient.java

public void executeDownloadFileRequest(File filename) throws MarketoException {
    String err;//from ww w . j  a va 2s  . c  om
    try {
        URL url = new URL(current_uri.toString());
        HttpsURLConnection urlConn = (HttpsURLConnection) url.openConnection();
        urlConn.setRequestMethod("GET");
        urlConn.setRequestProperty("accept", "text/json");
        int responseCode = urlConn.getResponseCode();
        if (responseCode == 200) {
            InputStream inStream = urlConn.getInputStream();
            FileUtils.copyInputStreamToFile(inStream, filename);
        } else {
            err = String.format("Download failed for %s. Status: %d", filename, responseCode);
            throw new MarketoException(REST, err);
        }
    } catch (IOException e) {
        err = String.format("Download failed for %s. Cause: %s", filename, e.getMessage());
        LOG.error(err);
        throw new MarketoException(REST, err);
    }
}

From source file:com.esri.geoevent.test.performance.bds.BdsEventConsumer.java

private int getMsLayerCount(String url) {
    int cnt = -1;

    try {//from ww w  .  j a v  a2s. c  om
        URL obj = new URL(url + "/query");
        HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

        //add request header
        con.setRequestMethod("POST");

        con.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
        con.setRequestProperty("Accept", "text/plain");

        String urlParameters = "where=" + URLEncoder.encode("1=1", "UTF-8") + "&returnCountOnly="
                + URLEncoder.encode("true", "UTF-8") + "&f=" + URLEncoder.encode("json", "UTF-8");

        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();

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

        //print result
        String jsonString = response.toString();

        JSONTokener tokener = new JSONTokener(jsonString);

        JSONObject root = new JSONObject(tokener);

        cnt = root.getInt("count");

    } catch (Exception e) {
        cnt = -2;
    } finally {
        return cnt;
    }

}

From source file:com.example.onenoteservicecreatepageexample.SendRefreshTokenAsyncTask.java

private Object[] attemptRefreshAccessToken(String refreshToken) throws Exception {
    /**//w  ww  . j a v a2 s . com
     * A new connection to the endpoint that processes requests for refreshing the access token
     */
    HttpsURLConnection refreshTokenConnection = (HttpsURLConnection) (new URL(MSA_TOKEN_REFRESH_URL))
            .openConnection();
    refreshTokenConnection.setDoOutput(true);
    refreshTokenConnection.setRequestMethod("POST");
    refreshTokenConnection.setDoInput(true);
    refreshTokenConnection.setRequestProperty("Content-Type", TOKEN_REFRESH_CONTENT_TYPE);
    refreshTokenConnection.connect();
    OutputStream refreshTokenRequestStream = null;
    try {
        refreshTokenRequestStream = refreshTokenConnection.getOutputStream();
        String requestBody = MessageFormat.format(TOKEN_REFRESH_REQUEST_BODY, Constants.CLIENTID,
                TOKEN_REFRESH_REDIRECT_URL, refreshToken);
        refreshTokenRequestStream.write(requestBody.getBytes());
        refreshTokenRequestStream.flush();
    } finally {
        if (refreshTokenRequestStream != null) {
            refreshTokenRequestStream.close();
        }
    }
    if (refreshTokenConnection.getResponseCode() == 200) {
        return parseRefreshTokenResponse(refreshTokenConnection);
    } else {
        throw new Exception("The attempt to refresh the access token failed");
    }
}

From source file:org.wso2.carbon.appmgt.sampledeployer.http.HttpHandler.java

public String doPostHttps(String backEnd, String payload, String your_session_id, String contentType)
        throws IOException {
    URL obj = new URL(backEnd);

    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
    //add reuqest header
    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", USER_AGENT);
    if (!your_session_id.equals("")) {
        con.setRequestProperty("Cookie", "JSESSIONID=" + your_session_id);
    }/*w  w  w. j a  va  2 s  .  co  m*/
    if (!contentType.equals("")) {
        con.setRequestProperty("Content-Type", contentType);
    }
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(payload);
    wr.flush();
    wr.close();
    int responseCode = con.getResponseCode();
    if (responseCode == 200) {
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        if (your_session_id.equals("")) {
            String session_id = response.substring((response.lastIndexOf(":") + 3),
                    (response.lastIndexOf("}") - 2));
            return session_id;
        } else if (your_session_id.equals("header")) {
            return con.getHeaderField("Set-Cookie");
        }

        return response.toString();
    }
    return null;
}

From source file:org.talend.components.marketo.runtime.client.MarketoBulkExecClient.java

public BulkImportResult executePostFileRequest(Class<?> resultClass, String filePath) throws MarketoException {
    String boundary = "Talend_tMarketoBulkExec_" + String.valueOf(System.currentTimeMillis());
    try {/*from  ww  w.  j  a  v a  2s .  com*/
        URL url = new URL(current_uri.toString());
        HttpsURLConnection urlConn = (HttpsURLConnection) url.openConnection();
        urlConn.setRequestMethod("POST");
        urlConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        urlConn.setRequestProperty("accept", "text/json");
        urlConn.setDoOutput(true);
        String requestBody = buildRequest(filePath); // build the request body
        PrintWriter wr = new PrintWriter(new OutputStreamWriter(urlConn.getOutputStream()));
        wr.append("--" + boundary + "\r\n");
        wr.append("Content-Disposition: form-data; name=\"file\";filename=\"" + filePath + "\";\r\n");
        wr.append("Content-type: text/plain; charset=\"utf-8\"\r\n");
        wr.append("Content-Transfer-Encoding: text/plain\r\n");
        wr.append("MIME-Version: 1.0\r\n");
        wr.append("\r\n");
        wr.append(requestBody);
        wr.append("\r\n");
        wr.append("--" + boundary);
        wr.flush();
        wr.close();
        int responseCode = urlConn.getResponseCode();
        if (responseCode == 200) {
            InputStream inStream = urlConn.getInputStream();
            InputStreamReader reader = new InputStreamReader(inStream);
            Gson gson = new Gson();
            return (BulkImportResult) gson.fromJson(reader, resultClass);
        } else {
            LOG.error("POST request failed: {}", responseCode);
            throw new MarketoException(REST, responseCode,
                    "Request failed! Please check your request setting!");
        }
    } catch (IOException e) {
        LOG.error("POST request failed: {}", e.getMessage());
        throw new MarketoException(REST, e.getMessage());
    }
}

From source file:com.esri.geoevent.test.tools.GetMapServiceCountRunnable.java

private int getMsLayerCount(String url) {
    int cnt = -1;

    try {/*from w ww .j a  va 2 s .c  o  m*/
        URL obj = new URL(url + "/query");
        HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

        //add reuqest header
        con.setRequestMethod("POST");

        con.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
        con.setRequestProperty("Accept", "text/plain");

        String urlParameters = "where=" + URLEncoder.encode("1=1", "UTF-8") + "&returnCountOnly="
                + URLEncoder.encode("true", "UTF-8") + "&f=" + URLEncoder.encode("json", "UTF-8");

        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();

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

        //print result
        String jsonString = response.toString();

        JSONTokener tokener = new JSONTokener(jsonString);

        JSONObject root = new JSONObject(tokener);

        cnt = root.getInt("count");

    } catch (Exception e) {
        cnt = -2;
    } finally {
        return cnt;
    }

}