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

private void login() {
    String url = null;//from  w  w w . j av  a2 s  . com

    try {
        //login
        url = ZONKY_URL + "oauth/token";
        String urlParameters = "username=" + userName + "&password=" + password
                + "&grant_type=password&scope=SCOPE_APP_WEB";
        byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);

        URL cookieUrl = new URL(url);
        HttpsURLConnection connection = (HttpsURLConnection) cookieUrl.openConnection();
        setupConnectionDefaults(connection);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Length", Integer.toString(postData.length));
        connection.setRequestProperty("Authorization", "Basic d2ViOndlYg==");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
            wr.write(postData);
        }
        String line = readResponse(connection);
        ZonkyTokenResponse response = gson.fromJson(line, ZonkyTokenResponse.class);
        token = response.getAccessToken();
        refreshToken = response.getRefreshToken();
        if (!token.isEmpty()) {
            logger.info("Successfully logged in to Zonky!");
        }
    } catch (MalformedURLException e) {
        logger.error("The URL '{}' is malformed", url, e);
    } catch (Exception e) {
        logger.error("Cannot get Zonky login token", e);
    }
}

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

private void HttpPost(String AccessTokenUri, String requestDetails) {
    InputStream inSt = null;/*from   ww  w .j  a v  a 2s . co m*/
    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:com.pearson.pdn.learningstudio.core.AbstractService.java

/**
 * Performs HTTP operations using the selected authentication method
 * /*from   w ww . java2 s.co  m*/
 * @param extraHeaders   Extra headers to include in the request
 * @param method   The HTTP Method to user
 * @param relativeUrl   The URL after .com (/me)
 * @param body   The body of the message
 * @return Output in the preferred data format
 * @throws IOException
 */
protected Response doMethod(Map<String, String> extraHeaders, HttpMethod method, String relativeUrl,
        String body) throws IOException {

    if (body == null) {
        body = "";
    }

    // append .xml extension when XML data format enabled.
    if (dataFormat == DataFormat.XML) {
        logger.debug("Using XML extension on route");

        String queryString = "";
        int queryStringIndex = relativeUrl.indexOf('?');
        if (queryStringIndex != -1) {
            queryString = relativeUrl.substring(queryStringIndex);
            relativeUrl = relativeUrl.substring(0, queryStringIndex);
        }

        String compareUrl = relativeUrl.toLowerCase();

        if (!compareUrl.endsWith(".xml")) {
            relativeUrl += ".xml";
        }

        if (queryStringIndex != -1) {
            relativeUrl += queryString;
        }
    }

    final String fullUrl = API_DOMAIN + relativeUrl;

    if (logger.isDebugEnabled()) {
        logger.debug("REQUEST - Method: " + method.name() + ", URL: " + fullUrl + ", Body: " + body);
    }

    URL url = new URL(fullUrl);
    Map<String, String> oauthHeaders = getOAuthHeaders(method, url, body);

    if (oauthHeaders == null) {
        throw new RuntimeException("Authentication method not selected. SEE useOAuth# methods");
    }

    if (extraHeaders != null) {
        for (String key : extraHeaders.keySet()) {
            if (!oauthHeaders.containsKey(key)) {
                oauthHeaders.put(key, extraHeaders.get(key));
            } else {
                throw new RuntimeException("Extra headers can not include OAuth headers");
            }
        }
    }

    HttpsURLConnection request = (HttpsURLConnection) url.openConnection();
    try {
        request.setRequestMethod(method.toString());

        Set<String> oauthHeaderKeys = oauthHeaders.keySet();
        for (String oauthHeaderKey : oauthHeaderKeys) {
            request.addRequestProperty(oauthHeaderKey, oauthHeaders.get(oauthHeaderKey));
        }

        request.addRequestProperty("User-Agent", getServiceIdentifier());

        if ((method == HttpMethod.POST || method == HttpMethod.PUT) && body.length() > 0) {
            if (dataFormat == DataFormat.XML) {
                request.setRequestProperty("Content-Type", "application/xml");
            } else {
                request.setRequestProperty("Content-Type", "application/json");
            }

            request.setRequestProperty("Content-Length", String.valueOf(body.getBytes("UTF-8").length));
            request.setDoOutput(true);

            DataOutputStream out = new DataOutputStream(request.getOutputStream());
            try {
                out.writeBytes(body);
                out.flush();
            } finally {
                out.close();
            }
        }

        Response response = new Response();
        response.setMethod(method.toString());
        response.setUrl(url.toString());
        response.setStatusCode(request.getResponseCode());
        response.setStatusMessage(request.getResponseMessage());
        response.setHeaders(request.getHeaderFields());

        InputStream inputStream = null;
        if (response.getStatusCode() < ResponseStatus.BAD_REQUEST.code()) {
            inputStream = request.getInputStream();
        } else {
            inputStream = request.getErrorStream();
        }

        boolean isBinary = false;
        if (inputStream != null) {
            StringBuilder responseBody = new StringBuilder();

            String contentType = request.getContentType();
            if (contentType != null) {
                if (!contentType.startsWith("text/") && !contentType.startsWith("application/xml")
                        && !contentType.startsWith("application/json")) { // assume binary
                    isBinary = true;
                    inputStream = new Base64InputStream(inputStream, true); // base64 encode
                }
            }

            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            try {
                String line = null;
                while ((line = bufferedReader.readLine()) != null) {
                    responseBody.append(line);
                }
            } finally {
                bufferedReader.close();
            }

            response.setContentType(contentType);

            if (isBinary) {
                String content = responseBody.toString();
                if (content.length() == 0) {
                    response.setBinaryContent(new byte[0]);
                } else {
                    response.setBinaryContent(Base64.decodeBase64(responseBody.toString()));
                }
            } else {
                response.setContent(responseBody.toString());
            }
        }

        if (logger.isDebugEnabled()) {
            if (isBinary) {
                logger.debug("RESPONSE - binary response omitted");
            } else {
                logger.debug("RESPONSE - " + response.toString());
            }
        }

        return response;
    } finally {
        request.disconnect();
    }

}

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

@Override
public Future<byte[]> getAvatarAsByteArray(FutureCallback<byte[]> callback) {
    ListenableFuture<byte[]> future = api.getThreadPool().getListeningExecutorService()
            .submit(new Callable<byte[]>() {
                @Override/*w  w w  .  ja v a 2 s.c  om*/
                public byte[] call() throws Exception {
                    logger.debug("Trying to get avatar from user {}", ImplUser.this);
                    if (avatarId == null) {
                        logger.debug("User {} seems to have no avatar. Returning empty array!", ImplUser.this);
                        return new byte[0];
                    }
                    URL url = new URL(
                            "https://discordapp.com/api/users/" + id + "/avatars/" + avatarId + ".jpg");
                    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[] avatar = out.toByteArray();
                    logger.debug("Got avatar from user {} (size: {})", ImplUser.this, avatar.length);
                    return avatar;
                }
            });
    if (callback != null) {
        Futures.addCallback(future, callback);
    }
    return future;
}

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

public Registration requestRegistrationAS() throws IOException {
    String clientName = "opPostmanTestRS"; // CLIENT_NAME_PREFIX +
    // System.currentTimeMillis();
    String clientCredentials = "client_credentials";
    String requestBodyRegistration = "{\"client_name\": \"" + clientName + "\",\"grant_types\": [\""
            + clientCredentials + "\"], \"id_token_signed_response_alg\":\"" + "HS256" + "\"}";

    // Registration
    URL urlRegistration = new URL(HTTPS_PREFIX + HOST + REQUEST_REGISTRATION_AS);

    HttpsURLConnection httpConRegistration = (HttpsURLConnection) urlRegistration.openConnection();
    httpConRegistration.setDoOutput(true);
    httpConRegistration.setRequestProperty("Host", REQUEST_HEADER_HOST);
    httpConRegistration.setRequestProperty("Content-Type", "application/json");
    httpConRegistration.setRequestProperty("Accept", "application/json");
    httpConRegistration.setRequestMethod("POST");

    OutputStream outRegistration = httpConRegistration.getOutputStream();
    outRegistration.write(requestBodyRegistration.getBytes());
    outRegistration.close();//from   w  w  w  .j  a  v  a 2s  . com

    int responseCodeRegistration = httpConRegistration.getResponseCode();
    log.info("responseCode Registration for " + urlRegistration + ": " + responseCodeRegistration);

    if (responseCodeRegistration == 201) {
        // everything ok
        InputStream isR = httpConRegistration.getInputStream();
        byte[] bisR = getBytesFromInputStream(isR);
        String jsonResponseRegistration = new String(bisR);
        log.info(jsonResponseRegistration);

        // extract the value of client_id (this value is called <c_id>in
        // the following) and the value of client_secret (called
        // <c_secret> in the following) from the JSON response

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

        JsonNode c_id = actualObj.get("client_id");
        JsonNode c_secret = actualObj.get("client_secret");

        if (c_id == null || c_id.getNodeType() != JsonNodeType.STRING || c_secret == null
                || c_secret.getNodeType() != JsonNodeType.STRING) {
            log.error("client_id: " + c_id);
            log.error("client_secret: " + c_secret);
        } else {
            // ok so far
            // Store <c_id> and <c_secret> for use during the token
            // acquisition
            log.info("client_id: " + c_id);
            log.info("client_secret: " + c_secret);

            return new Registration(c_id.textValue(), c_secret.textValue());
        }

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

    return null;
}

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

public Registration requestRegistrationAM() throws IOException {

    Registration registration = null;/*w ww .j  a v a2  s  .com*/

    String clientName = CLIENT_NAME_PREFIX + System.currentTimeMillis();
    String clientCredentials = "client_credentials";
    String requestBodyRegistration = "{\"client_name\": \"" + clientName + "\",\"grant_types\": [\""
            + clientCredentials + "\"]}";

    // Registration
    URL urlRegistration = new URL(HTTPS_PREFIX + HOST + REQUEST_REGISTRATION_AM);

    HttpsURLConnection httpConRegistration = (HttpsURLConnection) urlRegistration.openConnection();
    httpConRegistration.setDoOutput(true);
    httpConRegistration.setRequestProperty("Host", REQUEST_HEADER_HOST);
    httpConRegistration.setRequestProperty("Content-Type", "application/json");
    httpConRegistration.setRequestProperty("Accept", "application/json");
    httpConRegistration.setRequestMethod("POST");

    OutputStream outRegistration = httpConRegistration.getOutputStream();
    outRegistration.write(requestBodyRegistration.getBytes());
    outRegistration.close();

    int responseCodeRegistration = httpConRegistration.getResponseCode();
    log.info("responseCode Registration for " + urlRegistration + ": " + responseCodeRegistration);

    if (responseCodeRegistration == 201) {
        // everything ok
        InputStream isR = httpConRegistration.getInputStream();
        byte[] bisR = getBytesFromInputStream(isR);
        String jsonResponseRegistration = new String(bisR);
        log.info(jsonResponseRegistration);

        // extract the value of client_id (this value is called <c_id>in
        // the following) and the value of client_secret (called
        // <c_secret> in the following) from the JSON response

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

        JsonNode c_id = actualObj.get("client_id");
        JsonNode c_secret = actualObj.get("client_secret");

        if (c_id == null || c_id.getNodeType() != JsonNodeType.STRING || c_secret == null
                || c_secret.getNodeType() != JsonNodeType.STRING) {
            log.error("client_id: " + c_id);
            log.error("client_secret: " + c_secret);
        } else {
            // ok so far
            // Store <c_id> and <c_secret> for use during the token
            // acquisition
            log.info("client_id: " + c_id);
            log.info("client_secret: " + c_secret);

            registration = new Registration(c_id.textValue(), c_secret.textValue());
        }

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

    return registration;
}

From source file:org.openhab.binding.unifi.internal.UnifiBinding.java

private void logout() {
    URL url = null;/*from   ww  w .ja  v  a2s .  c  o m*/
    if (cookies.size() == 0)
        return;

    try {
        url = new URL(getControllerUrl("api/logout"));
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        connection.setInstanceFollowRedirects(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Cookie", cookies.get(0) + "; " + cookies.get(1));
        connection.getInputStream();
    } catch (MalformedURLException e) {
        logger.error("The URL '" + url + "' is malformed: " + e.toString());
    } catch (Exception e) {
        logger.error("Cannot do logout. Exception: " + e.toString());
    }
}

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 ww  . j  a v  a2 s.  c  o m*/
 * @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:me.rojo8399.placeholderapi.impl.Metrics.java

/**
 * Sends the data to the bStats server.//from ww  w.  ja v a2s .co  m
 *
 * @param data
 *            The data to send.
 * @throws Exception
 *             If the request failed.
 */
private static void sendData(JsonObject data) throws Exception {
    Validate.notNull(data, "Data cannot be null");
    HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();

    // Compress the data to save bandwidth
    byte[] compressedData = compress(data.toString());

    // Add headers
    connection.setRequestMethod("POST");
    connection.addRequestProperty("Accept", "application/json");
    connection.addRequestProperty("Connection", "close");
    connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip
    // our
    // request
    connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
    connection.setRequestProperty("Content-Type", "application/json"); // We
    // send
    // our
    // data
    // in
    // JSON
    // format
    connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);

    // Send data
    connection.setDoOutput(true);
    DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
    outputStream.write(compressedData);
    outputStream.flush();
    outputStream.close();

    connection.getInputStream().close(); // We don't care about the response
    // - Just send our data :)
}

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  . jav 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;
}