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:com.rmtheis.yandtran.YandexTranslatorAPI.java

/**
 * Forms an HTTPS request, sends it using GET method and returns the result of the request as a String.
 * /*from  w  w  w  .java  2s .  co m*/
 * @param url The URL to query for a String response.
 * @return The translated String.
 * @throws Exception on error.
 */
private static String retrieveResponse(final URL url) throws Exception {
    final HttpsURLConnection uc = (HttpsURLConnection) url.openConnection();
    if (referrer != null)
        uc.setRequestProperty("referer", referrer);
    uc.setRequestProperty("Content-Type", "text/plain; charset=" + ENCODING);
    uc.setRequestProperty("Accept-Charset", ENCODING);
    uc.setRequestMethod("GET");

    try {
        final int responseCode = uc.getResponseCode();
        final String result = inputStreamToString(uc.getInputStream());
        if (responseCode != 200) {
            throw new Exception("Error from Yandex API: " + result);
        }
        return result;
    } finally {
        if (uc != null) {
            uc.disconnect();
        }
    }
}

From source file:com.microsoft.office365.connectmicrosoftgraph.ConnectUnitTests.java

@BeforeClass
public static void getAccessTokenUsingPasswordGrant()
        throws IOException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException, JSONException {
    URL url = new URL(TOKEN_ENDPOINT);
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();

    String urlParameters = String.format(
            "grant_type=%1$s&resource=%2$s&client_id=%3$s&username=%4$s&password=%5$s", GRANT_TYPE,
            URLEncoder.encode(Constants.MICROSOFT_GRAPH_API_ENDPOINT_RESOURCE_ID, "UTF-8"), clientId, username,
            password);/*from   w w w .  j a  va2  s .c  o  m*/

    connection.setRequestMethod(REQUEST_METHOD);
    connection.setRequestProperty("Content-Type", CONTENT_TYPE);
    connection.setRequestProperty("Content-Length", String.valueOf(urlParameters.getBytes("UTF-8").length));

    connection.setDoOutput(true);
    DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream());
    dataOutputStream.writeBytes(urlParameters);
    dataOutputStream.flush();
    dataOutputStream.close();

    connection.getResponseCode();

    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

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

    JsonParser jsonParser = new JsonParser();
    JsonObject grantResponse = (JsonObject) jsonParser.parse(response.toString());
    accessToken = grantResponse.get("access_token").getAsString();
}

From source file:com.dmsl.anyplace.utils.NetworkUtils.java

public static InputStream downloadHttps(String urlS) throws IOException, URISyntaxException {
    InputStream is = null;/*  w  w  w.  j  ava2 s  .  co m*/

    URL url = new URL(encodeURL(urlS));

    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setReadTimeout(10000);
    conn.setConnectTimeout(15000);
    conn.setRequestMethod("GET");
    conn.setDoInput(true);

    conn.connect();

    int response = conn.getResponseCode();
    if (response == 200) {
        is = conn.getInputStream();
    }

    return is;
}

From source file:tk.egsf.ddns.JSON_helper.java

public static String postToUrl(String URL, String Auth, JSONObject post) {
    String ret = "";

    String https_url = URL;
    URL url;//  w  ww  . j  a  va2 s.  c o m
    try {

        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            @Override
            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        } };

        // Install the all-trusting trust manager
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

        url = new URL(https_url);
        HttpsURLConnection con = (HttpsURLConnection) url.openConnection();

        con.setRequestProperty("Authorization", Auth);
        con.setRequestProperty("Content-Type", "application/json");
        con.setRequestProperty("Accept", "application/json");
        con.setRequestMethod("POST");
        con.setDoOutput(true);
        con.connect();

        //          Send post
        System.out.println(post.toString());

        byte[] outputBytes = post.toString().getBytes("UTF-8");
        OutputStream os = con.getOutputStream();
        os.write(outputBytes);
        os.close();

        //            get response
        BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String input;
        while ((input = br.readLine()) != null) {
            ret += input;
        }
        br.close();

        System.out.println(ret);

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        //            e.printStackTrace();
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(login.class.getName()).log(Level.SEVERE, null, ex);
    } catch (KeyManagementException ex) {
        Logger.getLogger(login.class.getName()).log(Level.SEVERE, null, ex);
    }

    return ret;
}

From source file:org.wise.portal.presentation.web.filters.WISEAuthenticationProcessingFilter.java

/**
 * Check if the response is valid/*from   w  w w .jav a  2 s  . c  om*/
 * @param reCaptchaPrivateKey the ReCaptcha private key
 * @param reCaptchaPublicKey the ReCaptcha public key
 * @param gRecaptchaResponse the response
 * @return whether the user answered the ReCaptcha successfully
 */
public static boolean checkReCaptchaResponse(String reCaptchaPrivateKey, String reCaptchaPublicKey,
        String gRecaptchaResponse) {

    boolean isValid = false;

    //check if the public key is valid in case the admin entered it wrong
    boolean reCaptchaKeyValid = isReCaptchaKeyValid(reCaptchaPublicKey, reCaptchaPrivateKey);

    if (reCaptchaKeyValid && reCaptchaPrivateKey != null && reCaptchaPublicKey != null
            && gRecaptchaResponse != null && !gRecaptchaResponse.equals("")) {

        try {

            // the url to verify the response
            URL verifyURL = new URL("https://www.google.com/recaptcha/api/siteverify");
            HttpsURLConnection connection = (HttpsURLConnection) verifyURL.openConnection();
            connection.setRequestMethod("POST");

            // set the params
            String postParams = "secret=" + reCaptchaPrivateKey + "&response=" + gRecaptchaResponse;

            // make the request to verify if the user answered the ReCaptcha successfully
            connection.setDoOutput(true);
            DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
            outputStream.writeBytes(postParams);
            outputStream.flush();
            outputStream.close();

            BufferedReader bufferedReader = new BufferedReader(
                    new InputStreamReader(connection.getInputStream()));
            String inputLine = null;
            StringBuffer responseString = new StringBuffer();

            // read the response from the verify request
            while ((inputLine = bufferedReader.readLine()) != null) {
                responseString.append(inputLine);
            }

            bufferedReader.close();

            try {
                // create a JSON object from the response
                JSONObject responseObject = new JSONObject(responseString.toString());

                // get the value of the success field
                isValid = responseObject.getBoolean("success");
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return isValid;
}

From source file:com.scaniatv.ChallongeAPI.java

/**
 * @function readJsonFromUrl/*ww w  . java 2 s.  c o m*/
 *
 * @param {String} urlAddress
 */
@SuppressWarnings("UseSpecificCatch")
private static JSONObject readJsonFromUrl(String urlAddress, boolean isArray) {
    JSONObject jsonResult = new JSONObject("{}");
    InputStream inputStream = null;
    URL urlRaw;
    HttpsURLConnection urlConn;
    String jsonText = "";

    try {
        urlRaw = new URL(urlAddress);
        urlConn = (HttpsURLConnection) urlRaw.openConnection();
        urlConn.setDoInput(true);
        urlConn.setRequestMethod("GET");
        urlConn.addRequestProperty("Content-Type", "application/json");
        urlConn.addRequestProperty("Accept", "application/vnd.github.v3+json");
        urlConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 "
                + "(KHTML, like Gecko) Chrome/44.0.2403.52 Safari/537.36 PhantomBotJ/2015");
        urlConn.connect();

        if (urlConn.getResponseCode() == 200) {
            inputStream = urlConn.getInputStream();
        } else {
            inputStream = urlConn.getErrorStream();
        }

        BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
        jsonText = readAll(rd);
        if (isArray) {
            jsonResult = new JSONObject("{ \"array\": " + jsonText + " }");
        } else {
            jsonResult = new JSONObject(jsonText);
        }
        fillJSONObject(jsonResult, true, "GET", urlAddress, urlConn.getResponseCode(), "", "", jsonText);
    } catch (JSONException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "JSONException", ex.getMessage(), jsonText);
        com.gmt2001.Console.err.println("ChallongeAPI::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (NullPointerException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "NullPointerException", ex.getMessage(), "");
        com.gmt2001.Console.err.println("ChallongeAPI::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (MalformedURLException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "MalformedURLException", ex.getMessage(), "");
        com.gmt2001.Console.err.println("ChallongeAPI::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (SocketTimeoutException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "SocketTimeoutException", ex.getMessage(), "");
        com.gmt2001.Console.err.println("ChallongeAPI::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (IOException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "IOException", ex.getMessage(), "");
        com.gmt2001.Console.err.println("ChallongeAPI::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (Exception ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "Exception", ex.getMessage(), "");
        com.gmt2001.Console.err.println("ChallongeAPI::readJsonFromUrl::Exception: " + ex.getMessage());
    } finally {
        if (inputStream != null)
            try {
                inputStream.close();
            } catch (IOException ex) {
                fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "IOException", ex.getMessage(), "");
                com.gmt2001.Console.err.println("ChallongeAPI::readJsonFromUrl::Exception: " + ex.getMessage());
            }
    }

    return (jsonResult);
}

From source file:org.transitime.custom.missionBay.SfmtaApiCaller.java

/**
 * Posts the JSON string to the URL. For either the telemetry or the stop
 * command./*from   w  w  w .j a  v a2  s. c  om*/
 * 
 * @param baseUrl
 * @param jsonStr
 * @return True if successfully posted the data
 */
private static boolean post(String baseUrl, String jsonStr) {
    try {
        // Create the connection
        URL url = new URL(baseUrl);
        HttpsURLConnection con = (HttpsURLConnection) url.openConnection();

        // Set parameters for the connection
        con.setRequestMethod("POST");
        con.setRequestProperty("content-type", "application/json");
        con.setDoOutput(true);
        con.setDoInput(true);
        con.setUseCaches(false);

        // API now uses basic authentication
        String authString = login.getValue() + ":" + password.getValue();
        byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
        String authStringEnc = new String(authEncBytes);
        con.setRequestProperty("Authorization", "Basic " + authStringEnc);

        // Set the timeout so don't wait forever (unless timeout is set to 0)
        int timeoutMsec = timeout.getValue();
        con.setConnectTimeout(timeoutMsec);
        con.setReadTimeout(timeoutMsec);

        // Write the json data to the connection
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(jsonStr);
        wr.flush();
        wr.close();

        // Get the response
        int responseCode = con.getResponseCode();

        // If wasn't successful then log the response so can debug
        if (responseCode != 200) {
            String responseStr = "";
            if (responseCode != 500) {
                // Response code indicates there was a problem so get the
                // reply in case API returned useful error message
                InputStream inputStream = con.getErrorStream();
                if (inputStream != null) {
                    BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
                    String inputLine;
                    StringBuffer response = new StringBuffer();
                    while ((inputLine = in.readLine()) != null) {
                        response.append(inputLine);
                    }
                    in.close();
                    responseStr = response.toString();
                }
            }

            // Lot that response code indicates there was a problem
            logger.error(
                    "Bad HTTP response {} when writing data to SFMTA "
                            + "API. Response text=\"{}\" URL={} json=\n{}",
                    responseCode, responseStr, baseUrl, jsonStr);
        }

        // Done so disconnect just for the heck of it
        con.disconnect();

        // Return whether was successful
        return responseCode == 200;
    } catch (IOException e) {
        logger.error("Exception when writing data to SFMTA API: \"{}\" " + "URL={} json=\n{}", e.getMessage(),
                baseUrl, jsonStr);

        // Return that was unsuccessful
        return false;
    }

}

From source file:org.liberty.android.fantastischmemo.downloader.quizlet.lib.java

private static String makePostApiCall(URL url, String content, String authToken) throws IOException {
    HttpsURLConnection conn = null;
    OutputStreamWriter writer = null;
    String res = "";
    try {/*from   ww w  .  j  a  v  a2s.c  o m*/
        conn = (HttpsURLConnection) url.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.addRequestProperty("Authorization", "Bearer " + authToken);
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        writer = new OutputStreamWriter(conn.getOutputStream());
        writer.write(content);
        writer.close();

        if (conn.getResponseCode() / 100 >= 3) {
            Log.v("makePostApiCall", "Post content is: " + content);
            String error = "";
            try {
                JsonReader r = new JsonReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
                r.beginObject();
                while (r.hasNext()) {
                    error += r.nextName() + ": " + r.nextString() + "\r\n";
                }
                r.endObject();
                r.close();
            } catch (Throwable eex) {

            }
            Log.v("makePostApiCall", "Error string is: " + error);
            res = error;
            throw new IOException(
                    "Response code: " + conn.getResponseCode() + " URL is: " + url + " \nError: " + error);
        } else {
            JsonReader r = new JsonReader(new InputStreamReader(conn.getInputStream()));
            r.beginObject();
            while (r.hasNext()) {
                try {
                    res += r.nextName() + ": " + r.nextString() + "\n";
                } catch (Exception ex) {
                    r.skipValue();
                }
            }
            return res;
        }
    } finally {
        conn.disconnect();
        //return res;
    }
}

From source file:com.clearcenter.mobile_demo.mdRest.java

static public String Login(String host, String username, String password, String token) throws JSONException {
    if (password == null)
        Log.i(TAG, "Login by cookie, host: " + host + ", username: " + username);
    else/*from   w  w  w  .jav a 2s. c  o  m*/
        Log.i(TAG, "Login by password, host: " + host + ", username: " + username);

    try {
        URL url = new URL("https://" + host + URL_LOGIN);

        HttpsURLConnection http = CreateConnection(url);

        if (password != null) {
            // Setup HTTPS POST request
            String urlParams = "username=" + URLEncoder.encode(username, "UTF-8") + "&password="
                    + URLEncoder.encode(password, "UTF-8") + "&submit=submit";

            http.setRequestMethod("POST");
            http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            http.setRequestProperty("Content-Length", Integer.toString(urlParams.getBytes().length));

            // Write request
            DataOutputStream outputStream = new DataOutputStream(http.getOutputStream());
            outputStream.writeBytes(urlParams);
            outputStream.flush();
            outputStream.close();
        } else {
            http.setRequestMethod("GET");
            http.setRequestProperty("Cookie", token);
        }

        final StringBuffer response = ProcessRequest(http);

        // Process response
        JSONObject json_data = null;
        try {
            Log.i(TAG, "response: " + response.toString());
            json_data = new JSONObject(response.toString());
        } catch (JSONException e) {
            Log.e(TAG, "JSONException", e);
            return "";
        }
        if (json_data.has("result")) {
            final String cookie = http.getHeaderField("Set-Cookie");
            Integer result = RESULT_UNKNOWN;
            try {
                result = Integer.valueOf(json_data.getString("result"));
            } catch (NumberFormatException e) {
            }

            Log.i(TAG, "result: " + result.toString() + ", cookie: " + cookie);

            if (result == RESULT_SUCCESS) {
                if (cookie != null)
                    return cookie;
                else
                    return token;
            }

            // All other results are failures...
            return "";
        }
    } catch (Exception e) {
        Log.e(TAG, "Exception", e);
    }

    Log.i(TAG, "Malformed result");
    return "";
}

From source file:com.comcast.cdn.traffic_control.traffic_monitor.util.Fetcher.java

public static String fetchSecureContent(final String url, final int timeout) throws IOException {
    LOGGER.info("fetchSecureContent: " + url);
    final URL u = new URL(url);
    final URLConnection conn = u.openConnection();
    if (timeout != 0) {
        conn.setConnectTimeout(timeout);
        conn.setReadTimeout(timeout);//from   w  w w .j a  v a  2 s .com
    }
    if (conn instanceof HttpsURLConnection) {
        final HttpsURLConnection http = (HttpsURLConnection) conn;
        http.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(final String arg0, final SSLSession arg1) {
                return true;
            }
        });
        http.setRequestMethod(GET_STR);
        http.setAllowUserInteraction(true);
    }
    return IOUtils.toString(conn.getInputStream());
}