Example usage for javax.net.ssl HttpsURLConnection setRequestMethod

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

Introduction

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

Prototype

public void setRequestMethod(String method) throws ProtocolException 

Source Link

Document

Set the method for the URL request, one of:
  • GET
  • POST
  • HEAD
  • OPTIONS
  • PUT
  • DELETE
  • TRACE
are legal, subject to protocol restrictions.

Usage

From source file:org.wso2.carbon.identity.authenticator.PushAuthentication.java

/**
 * Prompt for a login and an OTP.// w w w .ja  v a2  s .  co m
 */
public JSONObject pushAuthenticate(String userId) throws AuthenticationFailedException {
    String urlParameters = null;
    JSONObject json = null;
    HttpsURLConnection conn = null;
    InputStream is = null;
    try {
        urlParameters = "action=pushAuthenticate" + "&serviceId="
                + URLEncoder.encode("" + serviceId, InweboConstants.ENCODING) + "&userId="
                + URLEncoder.encode(userId, InweboConstants.ENCODING) + "&format=json";
        if (this.context == null) {
            this.context = setHttpsClientCert(this.p12file, this.p12password);
        }
        SSLSocketFactory sslsocketfactory = context.getSocketFactory();
        URL url = new URL(urlString + urlParameters);
        conn = (HttpsURLConnection) url.openConnection();
        conn.setSSLSocketFactory(sslsocketfactory);
        conn.setRequestMethod("GET");
        is = conn.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is, InweboConstants.ENCODING));
        JSONParser parser = new JSONParser();
        json = (JSONObject) parser.parse(br);

    } catch (UnsupportedEncodingException e) {
        throw new AuthenticationFailedException("Error while encoding the URL" + e.getMessage(), e);
    } catch (MalformedURLException e) {
        throw new AuthenticationFailedException("Error while creating the URL" + e.getMessage(), e);
    } catch (ParseException e) {
        throw new AuthenticationFailedException("Error while parsing the json object" + e.getMessage(), e);
    } catch (Exception e) {
        throw new AuthenticationFailedException("Error while pushing authentication" + e.getMessage(), e);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
        try {
            if (is != null) {
                is.close();
            }
        } catch (IOException e) {
            throw new AuthenticationFailedException("Error while closing stream" + e.getMessage(), e);
        }
    }
    return json;
}

From source file:org.openhab.binding.jablotron.internal.JablotronBinding.java

private void login() {
    String url = null;//from  w w w  .jav  a  2s .c om

    try {
        //login
        stavA = 0;
        stavB = 0;
        stavABC = 0;
        stavPGX = 0;
        stavPGY = 0;

        url = JABLOTRON_URL + "ajax/login.php";
        String urlParameters = "login=" + email + "&heslo=" + password + "&aStatus=200&loginType=Login";
        byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);

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

        synchronized (session) {
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Referer", JABLOTRON_URL);
            connection.setRequestProperty("Content-Length", Integer.toString(postData.length));
            connection.setRequestProperty("X-Requested-With", "XMLHttpRequest");

            setConnectionDefaults(connection);
            try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
                wr.write(postData);
            }

            JablotronResponse response = new JablotronResponse(connection);
            if (response.getException() != null) {
                logger.error("JablotronResponse login exception: {}", response.getException());
                return;
            }

            if (!response.isOKStatus())
                return;

            //get cookie
            session = response.getCookie();

            //cloud request

            url = JABLOTRON_URL + "ajax/widget-new.php?" + getBrowserTimestamp();
            ;
            cookieUrl = new URL(url);
            connection = (HttpsURLConnection) cookieUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Referer", JABLOTRON_URL + "cloud");
            connection.setRequestProperty("Cookie", session);
            connection.setRequestProperty("X-Requested-With", "XMLHttpRequest");
            setConnectionDefaults(connection);

            //line = readResponse(connection);
            response = new JablotronResponse(connection);

            if (response.getException() != null) {
                logger.error("JablotronResponse widget exception: {}", response.getException().toString());
                return;
            }

            if (response.getResponseCode() != 200 || !response.isOKStatus()) {
                return;
            }

            if (response.getWidgetsCount() == 0) {
                logger.error("Cannot found any jablotron device");
                return;
            }
            service = response.getServiceId(0);

            //service request
            url = response.getServiceUrl(0);
            if (!services.contains(service)) {
                services.add(service);
                logger.info("Found Jablotron service: {} id: {}", response.getServiceName(0), service);
            }
            cookieUrl = new URL(url);
            connection = (HttpsURLConnection) cookieUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Referer", JABLOTRON_URL);
            connection.setRequestProperty("Cookie", session);
            connection.setRequestProperty("Upgrade-Insecure-Requests", "1");
            setConnectionDefaults(connection);

            if (connection.getResponseCode() == 200) {
                logger.debug("Successfully logged to Jablotron cloud!");
            } else {
                logger.error("Cannot log in to Jablotron cloud!");
            }
        }

    } catch (MalformedURLException e) {
        logger.error("The URL '{}' is malformed: {}", url, e.toString());
    } catch (Exception e) {
        logger.error("Cannot get Jablotron login cookie: {}", e.toString());
    }
}

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 o  m*/
    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;
}

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

public JSONObject makeWithdrawRequest(String accessToken, double amount, String currency, String owner,
        String accountNumber, String ifscCode) {
    HttpsURLConnection conn;
    DataOutputStream wr = null;/*from   w  w  w  .  ja  v  a  2s.c  o m*/
    JSONObject txnDetails = null;
    BufferedReader in = null;

    try {
        String url = urls.getString(base_url) + urls.getString(type);

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

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

        StringBuffer buff = new StringBuffer("amount=");
        buff.append(amount);

        buff.append("&currency=");
        buff.append(currency);

        buff.append("&owner=");
        buff.append(owner);

        buff.append("&account=");
        buff.append(accountNumber);

        buff.append("&ifsc=");
        buff.append(ifscCode);

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

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

        int responseCode = conn.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + buff.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:org.sufficientlysecure.keychain.ui.linked.LinkedIdCreateGithubFragment.java

private void revokeToken(final String token) {

    new AsyncTask<Void, Void, Void>() {
        @Override/*from  w ww  .  j  a  v a2  s .co  m*/
        protected Void doInBackground(Void... dummy) {
            try {
                HttpsURLConnection nection = (HttpsURLConnection) new URL("https://api.github.com/applications/"
                        + BuildConfig.GITHUB_CLIENT_ID + "/tokens/" + token).openConnection();
                nection.setRequestMethod("DELETE");
                String encoded = Base64.encodeToString(
                        (BuildConfig.GITHUB_CLIENT_ID + ":" + BuildConfig.GITHUB_CLIENT_SECRET).getBytes(),
                        Base64.DEFAULT);
                nection.setRequestProperty("Authorization", "Basic " + encoded);
                nection.connect();
            } catch (IOException e) {
                // nvm
            }
            return null;
        }
    }.execute();

}

From source file:com.tune.reporting.base.service.TuneServiceProxy.java

/**
 * Post request to TUNE Service API Service
 *
 * @return Boolean True if successful posting request, else False.
 * @throws TuneSdkException If error within SDK.
 *///from   w  w w. j  a v  a2s.c om
protected boolean postRequest() throws TuneSdkException {
    URL url = null;
    HttpsURLConnection conn = null;

    try {
        url = new URL(this.uri);
    } catch (MalformedURLException ex) {
        throw new TuneSdkException(String.format("Problems executing request: %s: %s: '%s'", this.uri,
                ex.getClass().toString(), ex.getMessage()), ex);
    }

    try {
        // connect to the server over HTTPS and submit the payload
        conn = (HttpsURLConnection) url.openConnection();

        // Create the SSL connection
        SSLContext sc;
        sc = SSLContext.getInstance("TLS");
        sc.init(null, null, new java.security.SecureRandom());
        conn.setSSLSocketFactory(sc.getSocketFactory());

        conn.setRequestMethod("GET");
        conn.setUseCaches(false);
        conn.setAllowUserInteraction(false);
        conn.connect();

        // Gets the status code from an HTTP response message.
        final int responseHttpCode = conn.getResponseCode();

        // Returns an unmodifiable Map of the header fields.
        // The Map keys are Strings that represent the response-header
        // field names. Each Map value is an unmodifiable List of Strings
        // that represents the corresponding field values.
        final Map<String, List<String>> responseHeaders = conn.getHeaderFields();

        final String requestUrl = url.toString();

        // Gets the HTTP response message, if any, returned along
        // with the response code from a server.
        String responseRaw = conn.getResponseMessage();

        // Pull entire JSON raw response
        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line + "\n");
        }
        br.close();

        responseRaw = sb.toString();

        // decode to JSON
        JSONObject responseJson = new JSONObject(responseRaw);

        this.response = new TuneServiceResponse(responseRaw, responseJson, responseHttpCode, responseHeaders,
                requestUrl.toString());
    } catch (Exception ex) {
        throw new TuneSdkException(String.format("Problems executing request: %s: '%s'",
                ex.getClass().toString(), ex.getMessage()), ex);
    }

    return true;
}

From source file:org.wso2.carbon.identity.authenticator.PushResult.java

/**
 * validate push result/*w  w w. jav a  2  s  . c  o m*/
 */
public JSONObject checkPushResult(String userId, String sessionId) throws AuthenticationFailedException {
    String urlParameters = null;
    JSONObject json = null;
    HttpsURLConnection conn = null;
    InputStream is = null;
    try {
        urlParameters = "action=checkPushResult" + "&serviceId="
                + URLEncoder.encode("" + serviceId, InweboConstants.ENCODING) + "&userId="
                + URLEncoder.encode(userId, InweboConstants.ENCODING) + "&sessionId="
                + URLEncoder.encode(sessionId, InweboConstants.ENCODING) + "&format=json";
        if (this.context == null) {
            this.context = PushAuthentication.setHttpsClientCert(this.p12file, this.p12password);
        }
        SSLSocketFactory sslsocketfactory = context.getSocketFactory();
        URL url = new URL(urlString + urlParameters);
        conn = (HttpsURLConnection) url.openConnection();
        conn.setSSLSocketFactory(sslsocketfactory);
        conn.setRequestMethod("GET");
        is = conn.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is, InweboConstants.ENCODING));
        JSONParser parser = new JSONParser();
        json = (JSONObject) parser.parse(br);
    } catch (UnsupportedEncodingException e) {
        throw new AuthenticationFailedException("Error while encoding the URL" + e.getMessage(), e);
    } catch (MalformedURLException e) {
        throw new AuthenticationFailedException("Error while creating the URL" + e.getMessage(), e);
    } catch (IOException e) {
        throw new AuthenticationFailedException("Error while creating the connection" + e.getMessage(), e);
    } catch (ParseException e) {
        throw new AuthenticationFailedException("Error while parsing the json object" + e.getMessage(), e);
    } catch (Exception e) {
        throw new AuthenticationFailedException("Error while pushing authentication" + e.getMessage(), e);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
        try {
            if (is != null) {
                is.close();
            }
        } catch (IOException e) {
            throw new AuthenticationFailedException("Error while closing stream" + e.getMessage(), e);
        }
    }
    return json;
}

From source file:org.wso2.carbon.identity.authenticator.wikid.WiKIDAuthenticator.java

/**
 * Send REST call/*w ww .jav  a2  s.  c  om*/
 */
private String sendRESTCall(String url, String urlParameters, String formParameters, String httpMethod) {
    String line;
    StringBuilder responseString = new StringBuilder();
    HttpsURLConnection connection = null;
    try {
        setHttpsClientCert(
                "/media/sf_SharedFoldersToVBox/is-connectors/wikid/wikid-authenticator/org.wso2.carbon.identity.authenticator/src/main/resources/localhostWiKID",
                "shakila");
        SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();

        URL wikidEP = new URL(url + urlParameters);
        connection = (HttpsURLConnection) wikidEP.openConnection();
        connection.setSSLSocketFactory(sslsocketfactory);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod(httpMethod);
        connection.setRequestProperty(WiKIDAuthenticatorConstants.HTTP_CONTENT_TYPE,
                WiKIDAuthenticatorConstants.HTTP_CONTENT_TYPE_XWFUE);
        if (httpMethod.toUpperCase().equals(WiKIDAuthenticatorConstants.HTTP_POST)) {
            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(),
                    WiKIDAuthenticatorConstants.CHARSET);
            writer.write(formParameters);
            writer.close();
        }
        if (connection.getResponseCode() == 200) {
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            while ((line = br.readLine()) != null) {
                responseString.append(line);
            }
            br.close();
        } else {
            return WiKIDAuthenticatorConstants.FAILED + WiKIDAuthenticatorConstants.REQUEST_FAILED;
        }
    } catch (ProtocolException e) {
        if (log.isDebugEnabled()) {
            log.debug(WiKIDAuthenticatorConstants.FAILED + e.getMessage());
        }
        return WiKIDAuthenticatorConstants.FAILED + e.getMessage();
    } catch (MalformedURLException e) {
        if (log.isDebugEnabled()) {
            log.debug(WiKIDAuthenticatorConstants.FAILED + e.getMessage());
        }
        return WiKIDAuthenticatorConstants.FAILED + e.getMessage();
    } catch (IOException e) {
        if (log.isDebugEnabled()) {
            log.debug(WiKIDAuthenticatorConstants.FAILED + e.getMessage());
        }
        return WiKIDAuthenticatorConstants.FAILED + e.getMessage();
    } finally {
        connection.disconnect();
    }
    return responseString.toString();
}

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);//  w  w w .  jav  a2  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.openecomp.sdc.ci.tests.datatypes.http.HttpRequest.java

public RestResponse httpsSendGet(String url, Map<String, String> headers) throws IOException {

    RestResponse restResponse = new RestResponse();
    URL obj = new URL(url);
    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
    // optional default is GET
    con.setRequestMethod("GET");
    // add request header
    if (headers != null) {
        for (Entry<String, String> header : headers.entrySet()) {
            String key = header.getKey();
            String value = header.getValue();
            con.setRequestProperty(key, value);
        }/*from   www  . j  ava2s . c  o  m*/

    }

    int responseCode = con.getResponseCode();
    logger.debug("Send GET http request, url: {}", url);
    logger.debug("Response Code: {}", responseCode);

    StringBuffer response = new StringBuffer();
    try {
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
    } catch (Exception e) {
        logger.debug("response body is null");
    }

    String result;

    try {

        result = IOUtils.toString(con.getErrorStream());
        response.append(result);

    } catch (Exception e2) {
        // result = null;
    }
    logger.debug("Response body: {}", response);

    // print result

    restResponse.setErrorCode(responseCode);

    if (response != null) {
        restResponse.setResponse(response.toString());
    }

    restResponse.setErrorCode(responseCode);
    // restResponse.setResponse(result);
    Map<String, List<String>> headerFields = con.getHeaderFields();
    restResponse.setHeaderFields(headerFields);
    String responseMessage = con.getResponseMessage();
    restResponse.setResponseMessage(responseMessage);

    con.disconnect();

    return restResponse;
}