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:com.denimgroup.threadfix.service.remoteprovider.VeracodeRemoteProvider.java

public void setupAuthorization(HttpsURLConnection connection, String username, String password) {
    String login = username + ":" + password;
    String encodedLogin = new String(Base64.encodeBase64(login.getBytes()));
    //String encodedLogin = Base64.encodeBase64String(login.getBytes());
    connection.setRequestProperty("Authorization", "Basic " + encodedLogin);
}

From source file:com.wso2telco.gsma.authenticators.mepin.MePinQuery.java

/**
 * Post request.// ww w .  j  a va2  s. co m
 *
 * @param url     the url
 * @param query   the query
 * @param charset the charset
 * @return the string
 * @throws IOException                  Signals that an I/O exception has occurred.
 * @throws XPathExpressionException     the x path expression exception
 * @throws SAXException                 the SAX exception
 * @throws ParserConfigurationException the parser configuration exception
 */
private String postRequest(String url, String query, String charset)
        throws IOException, XPathExpressionException, SAXException, ParserConfigurationException {

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

    ReadMobileConnectConfig readMobileConnectConfig = new ReadMobileConnectConfig();
    Map<String, String> readMobileConnectConfigResult;
    readMobileConnectConfigResult = readMobileConnectConfig.query("MePIN");
    connection.setDoOutput(true); // Triggers POST.
    connection.setRequestProperty("Accept-Charset", charset);
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);
    connection.setRequestProperty("Authorization", "Basic " + readMobileConnectConfigResult.get("AuthToken"));
    //        connection.setRequestProperty("Authorization", "Basic "+mePinConfig.getAuthToken());

    OutputStream output = connection.getOutputStream();
    String responseString = "";

    output.write(query.getBytes(charset));

    int status = connection.getResponseCode();

    if (log.isDebugEnabled()) {
        log.debug("MePIN Response Code :" + status);
    }

    try {
        switch (status) {
        case 200:
        case 201:
        case 400:
        case 403:
        case 404:
        case 500:
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line).append("\n");
            }
            br.close();
            responseString = sb.toString();
            break;
        }
    } catch (Exception httpex) {
        if (connection.getErrorStream() != null) {
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line).append("\n");
            }
            br.close();
            responseString = sb.toString();
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("MePIN Response :" + responseString);
    }
    return responseString;
}

From source file:com.microsoft.speech.tts.OxfordAuthentication.java

private void HttpPost(String AccessTokenUri, String requestDetails) {
    InputStream inSt = null;// w ww . j  a v a2s.c  om
    HttpsURLConnection webRequest = null;

    this.token = null;
    //Prepare OAuth request
    try {
        URL url = new URL(AccessTokenUri);
        webRequest = (HttpsURLConnection) url.openConnection();
        webRequest.setDoInput(true);
        webRequest.setDoOutput(true);
        webRequest.setConnectTimeout(5000);
        webRequest.setReadTimeout(5000);
        webRequest.setRequestProperty("content-type", "application/x-www-form-urlencoded");
        webRequest.setRequestMethod("POST");

        byte[] bytes = requestDetails.getBytes();
        webRequest.setRequestProperty("content-length", String.valueOf(bytes.length));
        webRequest.connect();

        DataOutputStream dop = new DataOutputStream(webRequest.getOutputStream());
        dop.write(bytes);
        dop.flush();
        dop.close();

        inSt = webRequest.getInputStream();
        InputStreamReader in = new InputStreamReader(inSt);
        BufferedReader bufferedReader = new BufferedReader(in);
        StringBuffer strBuffer = new StringBuffer();
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            strBuffer.append(line);
        }

        bufferedReader.close();
        in.close();
        inSt.close();
        webRequest.disconnect();

        // parse the access token from the json format
        String result = strBuffer.toString();
        JSONObject jsonRoot = new JSONObject(result);
        this.token = new OxfordAccessToken();

        if (jsonRoot.has("access_token")) {
            this.token.access_token = jsonRoot.getString("access_token");
        }

        if (jsonRoot.has("token_type")) {
            this.token.token_type = jsonRoot.getString("token_type");
        }

        if (jsonRoot.has("expires_in")) {
            this.token.expires_in = jsonRoot.getString("expires_in");
        }

        if (jsonRoot.has("scope")) {
            this.token.scope = jsonRoot.getString("scope");
        }
    } catch (Exception e) {
        Log.e(LOG_TAG, "Exception error", e);
    }
}

From source file:org.kontalk.upload.HTPPFileUploadConnection.java

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

    conn.setSSLSocketFactory(/*from w  w w  .  j a v a2 s  .  c  o m*/
            ClientHTTPConnection.setupSSLSocketFactory(mContext, null, null, acceptAnyCertificate));
    if (acceptAnyCertificate)
        conn.setHostnameVerifier(new AllowAllHostnameVerifier());
    conn.setRequestProperty("Content-Type", mime != null ? mime : "application/octet-stream");
    // bug caused by Lighttpd
    //conn.setRequestProperty("Expect", "100-continue");

    conn.setConnectTimeout(CONNECT_TIMEOUT);
    conn.setReadTimeout(READ_TIMEOUT);
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setRequestProperty("Content-Length", String.valueOf(length));
    conn.setRequestMethod("PUT");
}

From source file:de.escidoc.core.test.sb.HttpRequester.java

/**
 * Sends request with given method and given body to given URI and returns result as String.
 *
 * @param resource String resource//from   w  w w.j a  va 2s  .  com
 * @param method   String method
 * @param body     String body
 * @return String response
 * @throws Exception e
 */
private String requestSsl(final String resource, final String method, final String body) throws Exception {
    URL url;
    InputStream is = null;
    StringBuffer response = new StringBuffer();

    // Open Connection to given resource
    url = new URL(domain + resource);
    TrustManager[] tm = { new RelaxedX509TrustManager() };
    SSLContext sslContext = SSLContext.getInstance("SSL");
    sslContext.init(null, tm, new java.security.SecureRandom());
    SSLSocketFactory sslSF = sslContext.getSocketFactory();
    HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
    con.setSSLSocketFactory(sslSF);

    // Set Basic-Authentication Header
    if (securityHandle != null && !securityHandle.equals("")) {
        String encoding = new String(Base64.encodeBase64(securityHandle.getBytes(ClientBase.DEFAULT_CHARSET)));
        con.setRequestProperty("Authorization", "Basic " + encoding);
    }

    // Set request-method and timeout
    con.setRequestMethod(method.toUpperCase(Locale.ENGLISH));
    con.setReadTimeout(TIMEOUT);

    // If PUT or POST, write given body in Output-Stream
    if ((method.equalsIgnoreCase("PUT") || method.equalsIgnoreCase("POST")) && body != null) {
        con.setDoOutput(true);
        OutputStream out = con.getOutputStream();
        out.write(body.getBytes(ClientBase.DEFAULT_CHARSET));
        out.flush();
        out.close();
    }

    // Request
    is = con.getInputStream();

    // Read response
    String currentLine = null;
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    while ((currentLine = br.readLine()) != null) {
        response.append(currentLine + "\n");
    }
    is.close();
    return response.toString();
}

From source file:org.openhab.binding.zonky.internal.ZonkyBinding.java

private String logout() {
    String url = null;/*from   w ww .ja  va 2 s.c  om*/

    try {
        //login
        url = ZONKY_URL + "users/me/logout";

        URL cookieUrl = new URL(url);
        HttpsURLConnection connection = (HttpsURLConnection) cookieUrl.openConnection();
        setupConnectionDefaults(connection);
        connection.setRequestProperty("Authorization", "Bearer " + token);

        return readResponse(connection);
    } catch (MalformedURLException e) {
        logger.error("The URL '{}' is malformed", url, e);
    } catch (Exception e) {
        logger.error("Cannot get Zonky logout response", e);
    }
    return null;
}

From source file:net.roboconf.target.azure.internal.AzureIaasHandler.java

private int processPostRequest(URL url, byte[] data, String contentType, String keyStore,
        String keyStorePassword) throws GeneralSecurityException, IOException {

    SSLSocketFactory sslFactory = this.getSSLSocketFactory(keyStore, keyStorePassword);
    HttpsURLConnection con;
    con = (HttpsURLConnection) url.openConnection();
    con.setSSLSocketFactory(sslFactory);
    con.setDoOutput(true);//from  w w  w  .ja v  a 2 s. co  m
    con.setRequestMethod("POST");
    con.addRequestProperty("x-ms-version", "2014-04-01");
    con.setRequestProperty("Content-Length", String.valueOf(data.length));
    con.setRequestProperty("Content-Type", contentType);

    DataOutputStream requestStream = new DataOutputStream(con.getOutputStream());
    requestStream.write(data);
    requestStream.flush();
    requestStream.close();

    return con.getResponseCode();
}

From source file:org.openhab.binding.zonky.internal.ZonkyBinding.java

private String sendJsonRequest(String uri) {
    String url = null;/* w  w w  .j  a va 2  s .com*/

    logger.debug("sending uri request: {}", uri);
    try {
        //login
        url = ZONKY_URL + uri;

        URL cookieUrl = new URL(url);
        HttpsURLConnection connection = (HttpsURLConnection) cookieUrl.openConnection();
        setupConnectionDefaults(connection);
        connection.setRequestProperty("Authorization", "Bearer " + token);

        if (connection.getResponseCode() != 200) {
            logger.error("Got response code: {}", connection.getResponseCode());
            return null;
        }

        return readResponse(connection);
    } catch (MalformedURLException e) {
        logger.error("The URL '{}' is malformed", url, e);
    } catch (Exception e) {
        logger.error("Cannot get Zonky wallet response", e);
    }
    return null;
}

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

public String postput(Context context, final int httpType, final String uri, final StringEntity json)
        throws DigipostClientException, DigipostApiException, DigipostAuthenticationException {
    HttpsURLConnection httpsClient;
    InputStream result = null;/*from   w  ww.j av a 2  s. c  om*/
    try {
        URL url = new URL(uri);
        httpsClient = (HttpsURLConnection) url.openConnection();

        if (httpType == POST) {
            httpsClient.setRequestMethod("POST");
        } else if (httpType == PUT) {
            httpsClient.setRequestMethod("PUT");
        }
        httpsClient.setRequestProperty(ApiConstants.CONTENT_TYPE,
                ApiConstants.APPLICATION_VND_DIGIPOST_V2_JSON);
        httpsClient.setRequestProperty(ApiConstants.ACCEPT, ApiConstants.APPLICATION_VND_DIGIPOST_V2_JSON);
        httpsClient.setRequestProperty(ApiConstants.AUTHORIZATION,
                ApiConstants.BEARER + TokenStore.getAccess());

        OutputStream outputStream;
        outputStream = new BufferedOutputStream(httpsClient.getOutputStream());
        if (json != null) {
            json.writeTo(outputStream);
        }

        outputStream.flush();

        int statusCode = httpsClient.getResponseCode();

        try {
            NetworkUtilities.checkHttpStatusCode(context, statusCode);
        } catch (DigipostInvalidTokenException e) {
            OAuth.updateAccessTokenWithRefreshToken(context);
            return postput(context, httpType, uri, json);
        }

        if (statusCode == NetworkUtilities.HTTP_STATUS_NO_CONTENT) {
            return NetworkUtilities.SUCCESS_NO_CONTENT;
        }

        try {
            result = httpsClient.getInputStream();
        } catch (IllegalStateException e) {
            Log.e(TAG, e.getMessage());
        }

    } catch (IOException e) {
        throw new DigipostClientException(context.getString(R.string.error_your_network));
    }

    return JSONUtilities.getJsonStringFromInputStream(result);
}

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

/**
 * Creates a connection to the GCM server
 * @return The connection to the GCM server
 * @throws java.net.MalformedURLException
 * @throws java.io.IOException//from   w w w  .  j  a  va2s .  c o m
 */
private HttpsURLConnection createConnection() throws IOException {
    HttpsURLConnection conn;
    //retrieve the connection from the pool.
    conn = (HttpsURLConnection) new URL(this.sendURL).openConnection();
    conn.setRequestMethod("POST");
    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setRequestProperty("Content-Type", "application/json");
    conn.setRequestProperty("Authorization", "key=" + this.auth);
    return conn;
}