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: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.c o 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.openhab.binding.zonky.internal.ZonkyBinding.java

private void setupConnectionDefaults(HttpsURLConnection connection) {
    connection.setRequestProperty("User-Agent", USER_AGENT);
    connection.setRequestProperty("Accept-Language", "cs-CZ");
    //connection.setRequestProperty("Accept-Encoding", "gzip, deflate");
    connection.setRequestProperty("Accept", "application/json, text/plain, */*");
    connection.setRequestProperty("Referer", "https://app.zonky.cz/");
    connection.setInstanceFollowRedirects(false);
    connection.setUseCaches(false);//ww w  .  j a v  a 2  s .com
}

From source file:tetujin.nikeapi.core.JNikeLowLevelAPI.java

/**
 * /*from   www .  ja  v a  2  s. c o  m*/
 * @param con ?HttpsURLConnection 
 * @return con option??HttpsURLConnection
 */
protected HttpsURLConnection setHttpHeader(HttpsURLConnection con) {
    try {
        con.setRequestMethod(this.method);
        con.setDoOutput(true);
        con.setInstanceFollowRedirects(false);
        con.setRequestProperty("Accept-Language", this.lang);
        con.setRequestProperty("Accept", this.accept);
        con.setRequestProperty("appid", this.appid);
        System.out.println("Accept: " + con.getRequestProperty("Accept"));
        System.out.println("appid: " + con.getRequestProperty("appid"));
        return con;
    } catch (ProtocolException e) {
        e.printStackTrace();
        return con;
    }
}

From source file:com.vmware.photon.controller.deployer.deployengine.HttpFileServiceClient.java

private HttpsURLConnection createHttpConnection(URL destinationURL, String requestMethod) throws Exception {

    final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override/*from w  w  w  .jav  a 2 s  . c  o m*/
        public void checkClientTrusted(X509Certificate[] x509Certificates, String s)
                throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] x509Certificates, String s)
                throws CertificateException {
        }

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

    final HostnameVerifier trustAllHostnames = (String hostname, SSLSession sslSession) -> true;

    SSLContext sslContext = SSLContext.getInstance("SSL");
    sslContext.init(null, trustAllCerts, new SecureRandom());

    String authType = "Basic "
            + new String(Base64.encodeBase64((this.userName + ":" + this.password).getBytes()));

    HttpsURLConnection httpConnection = (HttpsURLConnection) destinationURL.openConnection();
    httpConnection.setSSLSocketFactory(sslContext.getSocketFactory());
    httpConnection.setHostnameVerifier(trustAllHostnames);
    httpConnection.setRequestMethod(requestMethod);
    httpConnection.setRequestProperty("Authorization", authType);
    return httpConnection;
}

From source file:com.persistent.cloudninja.scheduler.DeploymentMonitor.java

/**
 * Gets the information regarding the roles and their instances
 * of the deployment. It makes a call to REST API and gets the XML response. 
 * /*w  ww .ja v a  2s . c o  m*/
 * @return XML response
 * @throws IOException
 */
public StringBuffer getRoleInfoForDeployment() throws IOException {
    StringBuffer response = new StringBuffer();
    System.setProperty("javax.net.ssl.keyStoreType", "pkcs12");

    StringBuffer keyStore = new StringBuffer();
    keyStore.append(System.getProperty("java.home"));
    LOGGER.debug("java.home : " + keyStore.toString());
    if (keyStore.length() == 0) {
        keyStore.append(System.getenv("JRE_HOME"));
        LOGGER.debug("JRE_HOME : " + keyStore.toString());
    }
    keyStore.append(File.separator + "lib\\security\\CloudNinja.pfx");
    System.setProperty("javax.net.ssl.keyStore", keyStore.toString());
    System.setProperty("javax.net.debug", "ssl");
    System.setProperty("javax.net.ssl.keyStorePassword", keyStorePassword);
    System.setProperty("javax.net.ssl.trustStorePassword", trustStorePassword);

    SSLSocketFactory sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
    // form the URL which will return the response
    // containing info of roles and their instances.
    StringBuffer strURL = new StringBuffer(host);
    strURL.append(subscriptionId);
    strURL.append("/services/hostedservices/");
    strURL.append(hostedServiceName);
    strURL.append("/deploymentslots/");
    strURL.append(deploymentType);

    URL url = new URL(strURL.toString());

    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
    connection.setSSLSocketFactory(sslSocketFactory);
    connection.setRequestMethod("GET");
    connection.setAllowUserInteraction(false);
    // set the x-ms-version in header which is a compulsory parameter to get response 
    connection.setRequestProperty("x-ms-version", "2011-10-01");
    connection.setRequestProperty("Content-type", "text/xml");
    connection.setRequestProperty("accept", "text/xml");
    // get the response as input stream
    InputStream inputStream = connection.getInputStream();
    InputStreamReader streamReader = new InputStreamReader(inputStream);
    BufferedReader bufferedReader = new BufferedReader(streamReader);
    String string = null;
    while ((string = bufferedReader.readLine()) != null) {
        response.append(string);
    }
    return response;
}

From source file:org.wso2.carbon.identity.authenticator.mepin.MepinTransactions.java

protected String getTransaction(String url, String transactionId, String clientId, String username,
        String password) throws IOException {

    log.debug("Started handling transaction creation");
    String authStr = username + ":" + password;
    String encoding = new String(Base64.encodeBase64(authStr.getBytes()));
    HttpsURLConnection connection = null;
    String responseString = "";

    url = url + "?transaction_id=" + transactionId + "&client_id=" + clientId;
    try {//from   w ww  .j  a  va 2 s .c  o  m
        connection = (HttpsURLConnection) new URL(url).openConnection();

        connection.setRequestMethod(MepinConstants.HTTP_GET);
        connection.setRequestProperty(MepinConstants.HTTP_ACCEPT, MepinConstants.HTTP_CONTENT_TYPE);
        connection.setRequestProperty(MepinConstants.HTTP_AUTHORIZATION,
                MepinConstants.HTTP_AUTHORIZATION_BASIC + encoding);

        String response = "";
        int statusCode = connection.getResponseCode();
        InputStream is;
        if ((statusCode == 200) || (statusCode == 201)) {
            is = connection.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String output;
            while ((output = br.readLine()) != null) {
                responseString += output;
            }
            br.close();
        } else {
            is = connection.getErrorStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String output;
            while ((output = br.readLine()) != null) {
                responseString += output;
            }
            br.close();
            if (log.isDebugEnabled()) {
                log.debug("MePIN Status Response: " + response);
            }
            return MepinConstants.FAILED;
        }

    } catch (IOException e) {
        throw new IOException(e.getMessage(), e);
    } finally {
        connection.disconnect();
    }
    return responseString;
}

From source file:de.thingweb.client.security.Security4NicePlugfest.java

public String requestASToken(Registration registration, String[] adds) throws IOException {
    String asToken = null;//from www  . j  av  a  2 s. c o  m

    // Token Acquisition
    // Create a HTTP request as in the following prototype and send
    // it via TLS to the AM
    //
    // Token Acquisition
    // Create a HTTP request as in the following prototype and send
    // it via TLS to the AM
    // Request
    // POST /iam-services/0.1/oidc/am/token HTTP/1.1
    URL urlTokenAcquisition = new URL(HTTPS_PREFIX + HOST + REQUEST_TOKEN_AQUISITION);

    HttpsURLConnection httpConTokenAcquisition = (HttpsURLConnection) urlTokenAcquisition.openConnection();
    httpConTokenAcquisition.setDoOutput(true);
    httpConTokenAcquisition.setRequestProperty("Host", REQUEST_HEADER_HOST);
    httpConTokenAcquisition.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    httpConTokenAcquisition.setRequestProperty("Accept", "application/json");
    // httpConTokenAcquisition.setRequestProperty("Authorization",
    // "Basic Base64(<c_id>:<c_secret>");
    String auth = registration.c_id + ":" + registration.c_secret;
    String authb = "Basic " + new String(Base64.getEncoder().encode(auth.getBytes()));
    httpConTokenAcquisition.setRequestProperty("Authorization", authb);
    httpConTokenAcquisition.setRequestMethod("POST");

    String requestBodyTokenAcquisition = "grant_type=client_credentials";
    if (adds == null || adds.length == 0) {
        // no additions
    } else {
        if (adds.length % 2 == 0) {
            for (int i = 0; i < (adds.length - 1); i += 2) {
                requestBodyTokenAcquisition += "&";
                requestBodyTokenAcquisition += URLEncoder.encode(adds[i], "UTF-8");
                requestBodyTokenAcquisition += "=";
                requestBodyTokenAcquisition += URLEncoder.encode(adds[i + 1], "UTF-8");
            }
        } else {
            log.warn(
                    "Additional information for token not used! Not a multiple of 2: " + Arrays.toString(adds));
        }
    }

    OutputStream outTokenAcquisition = httpConTokenAcquisition.getOutputStream();
    outTokenAcquisition.write(requestBodyTokenAcquisition.getBytes());
    outTokenAcquisition.close();

    int responseCodeoutTokenAcquisition = httpConTokenAcquisition.getResponseCode();
    log.info("responseCode TokenAcquisition for " + urlTokenAcquisition + ": "
            + responseCodeoutTokenAcquisition);

    if (responseCodeoutTokenAcquisition == 200) {
        // everything ok
        InputStream isTA = httpConTokenAcquisition.getInputStream();
        byte[] bisTA = getBytesFromInputStream(isTA);
        String jsonResponseTA = new String(bisTA);
        log.info(jsonResponseTA);

        ObjectMapper mapper = new ObjectMapper();
        JsonFactory factory = mapper.getFactory();
        JsonParser jp = factory.createParser(bisTA);
        JsonNode actualObj = mapper.readTree(jp);

        JsonNode access_token = actualObj.get("access_token");
        if (access_token == null || access_token.getNodeType() != JsonNodeType.STRING) {
            log.error("access_token: " + access_token);
        } else {
            // ok so far
            // access_token provides a JWT structure
            // see Understanding JWT
            // https://developer.atlassian.com/static/connect/docs/latest/concepts/understanding-jwt.html

            log.info("access_token: " + access_token);
            // http://jwt.io/

            // TODO verify signature (e.g., use Jose4J)

            // Note: currently we assume signature is fine.. we just fetch
            // "as_token"
            String[] decAT = access_token.textValue().split("\\.");
            if (decAT == null || decAT.length != 3) {
                log.error("Cannot build JWT tripple structure for " + access_token);
            } else {
                assert (decAT.length == 3);
                // JWT structure
                // decAT[0]; // header
                // decAT[1]; // payload
                // decAT[2]; // signature
                String decAT1 = new String(Base64.getDecoder().decode(decAT[1]));
                JsonParser jpas = factory.createParser(decAT1);
                JsonNode payload = mapper.readTree(jpas);
                JsonNode as_token = payload.get("as_token");
                if (as_token == null || as_token.getNodeType() != JsonNodeType.STRING) {
                    log.error("as_token: " + as_token);
                } else {
                    log.info("as_token: " + as_token);
                    asToken = as_token.textValue();
                }
            }
        }

    } else {
        // error
        InputStream error = httpConTokenAcquisition.getErrorStream();
        byte[] berror = getBytesFromInputStream(error);
        log.error(new String(berror));
    }

    httpConTokenAcquisition.disconnect();

    return asToken;
}

From source file:com.apteligent.ApteligentJavaClient.java

private HttpsURLConnection sendGetRequest(String endpoint, String urlParameters) throws IOException {
    // build connection object for GET request
    URL obj = new URL(endpoint + urlParameters);
    HttpsURLConnection conn = (HttpsURLConnection) obj.openConnection();
    conn.setSSLSocketFactory((SSLSocketFactory) SSLSocketFactory.getDefault());
    conn.setDoOutput(false);/* w  ww  .  ja v a2 s . c o  m*/
    conn.setDoInput(true);
    conn.setRequestProperty("Authorization", "Bearer " + this.token.getAccessToken());
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setRequestProperty("Accept", "*/*");
    conn.setRequestMethod("GET");
    return conn;
}

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

private void HttpPost(String AccessTokenUri, String apiKey) {
    InputStream inSt = null;/* www.  j a v a2  s  . c om*/
    HttpsURLConnection webRequest = null;

    this.accessToken = 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("Ocp-Apim-Subscription-Key", apiKey);
        webRequest.setRequestMethod("POST");

        String request = "";
        byte[] bytes = request.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();

        this.accessToken = strBuffer.toString();

    } catch (Exception e) {
        Log.e(LOG_TAG, "Exception error", e);
    }
}

From source file:com.apteligent.ApteligentJavaClient.java

private HttpsURLConnection sendPostRequest(String endpoint, String params) throws IOException {
    // build conn object for POST request
    URL obj = new URL(endpoint);
    HttpsURLConnection conn = (HttpsURLConnection) obj.openConnection();
    conn.setSSLSocketFactory((SSLSocketFactory) SSLSocketFactory.getDefault());
    conn.setDoOutput(true);//from w w w  . j  a  v  a 2  s  . c  om
    conn.setDoInput(true);
    conn.setRequestProperty("Authorization", "Bearer " + this.token.getAccessToken());
    conn.setRequestProperty("Content-Type", "application/json");
    conn.setRequestProperty("Accept", "*/*");
    conn.setRequestProperty("Content-Length", Integer.toString(params.getBytes().length));
    conn.setRequestMethod("POST");

    // Send post request
    DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
    wr.writeBytes(params);
    wr.flush();
    wr.close();
    return conn;
}