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.simiacryptus.util.Util.java

/**
 * Cache input stream.//w w w.  ja v  a2s.  c  o  m
 *
 * @param url  the url
 * @param file the file
 * @return the input stream
 * @throws IOException              the io exception
 * @throws NoSuchAlgorithmException the no such algorithm exception
 * @throws KeyStoreException        the key store exception
 * @throws KeyManagementException   the key management exception
 */
public static InputStream cache(String url, String file)
        throws IOException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
    if (new File(file).exists()) {
        return new FileInputStream(file);
    } else {
        TrustManager[] trustManagers = { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }

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

            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        } };
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(null, trustManagers, null);
        SSLSocketFactory sslFactory = ctx.getSocketFactory();
        URLConnection urlConnection = new URL(url).openConnection();
        if (urlConnection instanceof javax.net.ssl.HttpsURLConnection) {
            HttpsURLConnection conn = (HttpsURLConnection) urlConnection;
            conn.setSSLSocketFactory(sslFactory);
            conn.setRequestMethod("GET");
        }
        InputStream inputStream = urlConnection.getInputStream();
        FileOutputStream cache = new FileOutputStream(file);
        return new TeeInputStream(inputStream, cache);
    }
}

From source file:org.openhab.binding.whistle.internal.WhistleBinding.java

protected static String getAuthToken(String username, String password) throws Exception {
    logger.debug("Using username: '{}' / password: '{}'", username, password);

    URL obj = new URL(APIROOT + "tokens.json");
    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
    // add request headers and parameters
    con.setDoOutput(true);// w ww  .j  ava2  s .c  om
    con.setRequestProperty("Content-Type", "application/json");
    con.setRequestProperty("User-Agent", "WhistleApp/102 (iPhone; iOS 7.0.4; Scale/2.00)");
    con.setRequestMethod("POST");
    String urlParameters = "{\"password\":\"" + password + "\",\"email\":\"" + username
            + "\",\"app_id\":\"com.whistle.WhistleApp\"}";
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.flush();
    wr.close();
    if (con.getResponseCode() != 200) {
        logger.error("Username / password combination didn't work. Failed to get AuthenticationToken");
        return null;
    }
    // Read the buffer
    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String response = in.readLine();
    in.close();
    // Parse the data and return the token
    JsonObject jobj = new Gson().fromJson(response, JsonObject.class);
    return jobj.get("token").getAsString();
}

From source file:com.hybris.mobile.data.WebServiceDataProvider.java

/**
 * Synchronous call to get a new client credentials token, required for creating new account
 * /*w w  w . ja  v a  2s.  c o m*/
 * @param url
 * @param clientCredentialsToken
 * @param httpMethod
 * @param httpBody
 * @return The data from the server as a string, in almost all cases JSON
 * @throws MalformedURLException
 * @throws IOException
 * @throws ProtocolException
 * @throws JSONException
 */
public static String getClientCredentialsResponse(Context context, String url, String clientCredentialsToken,
        String httpMethod, Bundle httpBody)
        throws MalformedURLException, IOException, ProtocolException, JSONException {
    boolean refreshLimitReached = false;
    int refreshed = 0;

    String response = "";
    while (!refreshLimitReached) {
        // If we have refreshed max number of times, we will not do so again
        if (refreshed == 1) {
            refreshLimitReached = true;
        }

        HttpsURLConnection connection = createSecureConnection(new URL(addParameters(context, url)));
        trustAllHosts();
        connection.setHostnameVerifier(DO_NOT_VERIFY);
        connection.setRequestMethod(httpMethod);
        connection.setDoOutput(true);
        connection.setDoInput(true);
        String authValue = "Bearer " + clientCredentialsToken;
        connection.setRequestProperty("Authorization", authValue);
        connection.connect();

        if (!httpBody.isEmpty()) {
            OutputStream os = new BufferedOutputStream(connection.getOutputStream());
            os.write(encodePostBody(httpBody).getBytes());
            os.flush();
        }

        try {
            LoggingUtils.d(LOG_TAG, connection.toString());
            response = readFromStream(connection.getInputStream());
        } catch (FileNotFoundException e) {
            response = readFromStream(connection.getErrorStream());
        } finally {
            connection.disconnect();
        }

        // Allow for calls to return nothing
        if (response.length() == 0) {
            return "";
        }

        // Check for JSON parsing errors (will throw JSONException is can't be parsed)
        JSONObject object = new JSONObject(response);

        // If no error, return response
        if (!object.has("error")) {
            return response;
        }
        // If there is a refresh token error, refresh the token
        else if (object.getString("error").equals("invalid_token")) {
            if (refreshLimitReached) {
                // Give up
                return response;
            } else {
                // Refresh the token
                WebServiceAuthProvider.refreshAccessToken(context);
                refreshed++;
            }
        }
    } // while(!refreshLimitReached)

    return response;
}

From source file:com.gson.util.HttpKit.java

/**
 * ?http?//from w  w w  .ja va 2 s.  com
 * @param url
 * @param method
 * @return
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws KeyManagementException
 */
private static HttpsURLConnection initHttps(String url, String method, Map<String, String> headers)
        throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
    TrustManager[] tm = { new MyX509TrustManager() };
    System.setProperty("https.protocols", "SSLv3");
    SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
    sslContext.init(null, tm, new java.security.SecureRandom());
    // SSLContextSSLSocketFactory  
    SSLSocketFactory ssf = sslContext.getSocketFactory();
    URL _url = new URL(url);
    HttpsURLConnection http = (HttpsURLConnection) _url.openConnection();
    // ??
    http.setHostnameVerifier(new HttpKit().new TrustAnyHostnameVerifier());
    // 
    http.setConnectTimeout(25000);
    // ? --??
    http.setReadTimeout(25000);
    http.setRequestMethod(method);
    http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    http.setRequestProperty("User-Agent",
            "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");
    if (null != headers && !headers.isEmpty()) {
        for (Entry<String, String> entry : headers.entrySet()) {
            http.setRequestProperty(entry.getKey(), entry.getValue());
        }
    }
    http.setSSLSocketFactory(ssf);
    http.setDoOutput(true);
    http.setDoInput(true);
    http.connect();
    return http;
}

From source file:com.hichengdai.qlqq.front.util.HttpKit.java

/**
 * ?http?//  ww w  .  ja  v  a 2  s.  c  o m
 * 
 * @param url
 * @param method
 * @return
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws KeyManagementException
 */
private static HttpsURLConnection initHttps(String url, String method, Map<String, String> headers)
        throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
    TrustManager[] tm = { new MyX509TrustManager() };
    SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
    sslContext.init(null, tm, new java.security.SecureRandom());
    // SSLContextSSLSocketFactory
    SSLSocketFactory ssf = sslContext.getSocketFactory();
    URL _url = new URL(url);
    HttpsURLConnection http = (HttpsURLConnection) _url.openConnection();
    // ??
    http.setHostnameVerifier(new HttpKit().new TrustAnyHostnameVerifier());
    // 
    http.setConnectTimeout(25000);
    // ? --??
    http.setReadTimeout(25000);
    http.setRequestMethod(method);
    http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    http.setRequestProperty("User-Agent",
            "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");
    if (null != headers && !headers.isEmpty()) {
        for (Entry<String, String> entry : headers.entrySet()) {
            http.setRequestProperty(entry.getKey(), entry.getValue());
        }
    }
    http.setSSLSocketFactory(ssf);
    http.setDoOutput(true);
    http.setDoInput(true);
    http.connect();
    return http;
}

From source file:com.simiacryptus.util.Util.java

/**
 * Get input stream./* w ww.  ja v a  2  s  .  co  m*/
 *
 * @param url the url
 * @return the input stream
 * @throws NoSuchAlgorithmException the no such algorithm exception
 * @throws KeyManagementException   the key management exception
 * @throws IOException              the io exception
 */
public static InputStream get(@javax.annotation.Nonnull String url)
        throws NoSuchAlgorithmException, KeyManagementException, IOException {
    @javax.annotation.Nonnull
    final TrustManager[] trustManagers = { new X509TrustManager() {
        @Override
        public void checkClientTrusted(final X509Certificate[] certs, final String authType) {
        }

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

        @javax.annotation.Nonnull
        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    } };
    @javax.annotation.Nonnull
    final SSLContext ctx = SSLContext.getInstance("TLS");
    ctx.init(null, trustManagers, null);
    final SSLSocketFactory sslFactory = ctx.getSocketFactory();
    final URLConnection urlConnection = new URL(url).openConnection();
    if (urlConnection instanceof HttpsURLConnection) {
        @javax.annotation.Nonnull
        final HttpsURLConnection conn = (HttpsURLConnection) urlConnection;
        conn.setSSLSocketFactory(sslFactory);
        conn.setRequestMethod("GET");
    }
    return urlConnection.getInputStream();
}

From source file:com.microsoft.office365.msgraphsnippetapp.SnippetsUnitTests.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(ServiceConstants.AUTHENTICATION_RESOURCE_ID, "UTF-8"), clientId, username,
            password);//from   w  ww . j  av a2 s.co 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;
    StringBuilder response = new StringBuilder();

    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();

    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    logging.setLevel(HttpLoggingInterceptor.Level.BODY);

    OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            request = request.newBuilder().addHeader("Authorization", "Bearer " + accessToken)
                    // This header has been added to identify this sample in the Microsoft Graph service.
                    // If you're using this code for your project please remove the following line.
                    .addHeader("SampleID", "android-java-snippets-rest-sample").build();

            return chain.proceed(request);
        }
    }).addInterceptor(logging).build();

    Retrofit retrofit = new Retrofit.Builder().baseUrl(ServiceConstants.AUTHENTICATION_RESOURCE_ID)
            .client(client).addConverterFactory(GsonConverterFactory.create()).build();

    contactService = retrofit.create(MSGraphContactService.class);
    drivesService = retrofit.create(MSGraphDrivesService.class);
    eventsService = retrofit.create(MSGraphEventsService.class);
    groupsService = retrofit.create(MSGraphGroupsService.class);
    mailService = retrofit.create(MSGraphMailService.class);
    meService = retrofit.create(MSGraphMeService.class);
    userService = retrofit.create(MSGraphUserService.class);

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss", Locale.US);
    dateTime = simpleDateFormat.format(new Date());
}

From source file:eu.siacs.conversations.ui.ServiceBrowserFragment.java

public static boolean exists(String URLName) {

    X509TrustManager trustManager = new X509TrustManager() {

        @Override/*from  w w w .j  a v  a  2s  .co m*/
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            // NOTE : This is where we can calculate the certificate's fingerprint,
            // show it to the user and throw an exception in case he doesn't like it
        }

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }
    };

    // Create a trust manager that does not validate certificate chains
    X509TrustManager[] trustAllCerts = new X509TrustManager[] { trustManager };

    // Install the all-trusting trust manager
    SSLSocketFactory noSSLv3Factory = null;
    try {
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
            noSSLv3Factory = new TLSSocketFactory(trustAllCerts, new SecureRandom());
        } else {
            noSSLv3Factory = sc.getSocketFactory();
        }
        HttpsURLConnection.setDefaultSSLSocketFactory(noSSLv3Factory);
    } catch (GeneralSecurityException e) {
    }

    try {
        HttpsURLConnection.setFollowRedirects(false);
        // note : you may also need
        //        HttpURLConnection.setInstanceFollowRedirects(false)
        URL url = new URL(URLName);
        HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
        con.setSSLSocketFactory(noSSLv3Factory);
        con.setRequestProperty("Accept-Encoding", "");
        //HttpsURLConnection.setDefaultHostnameVerifier(new NullHostNameVerifier());
        con.setHostnameVerifier(new NullHostNameVerifier(url.getHost()));
        con.setRequestMethod("HEAD");
        return (con.getResponseCode() == HttpsURLConnection.HTTP_OK);
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

From source file:ovh.tgrhavoc.aibot.RealmsUtil.java

private static String mcoapiGet(String address, YggdrasilSession session, ProxyData proxy) throws IOException {
    Proxy wrappedProxy = wrapProxy(proxy);
    HttpsURLConnection connection;
    if (wrappedProxy != null)
        connection = (HttpsURLConnection) new URL(address).openConnection(wrappedProxy);
    else//from  w  w w  . j a v  a  2s. com
        connection = (HttpsURLConnection) new URL(address).openConnection();

    connection.addRequestProperty("Cookie", "user=" + session.getUsername() + ";version=1.7.2;sid=token:"
            + session.getAccessToken().toString(16) + ":" + session.getSelectedProfile().getId());
    connection.setUseCaches(false);
    connection.setDoOutput(true);
    connection.setDoOutput(true);
    connection.setRequestMethod("GET");

    connection.connect();

    InputStream in = connection.getInputStream();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int read;
    while ((read = in.read(buffer)) != -1)
        out.write(buffer, 0, read);

    return new String(out.toByteArray());
}

From source file:com.hybris.mobile.data.WebServiceDataProvider.java

/**
 * Synchronous call for logging in//from ww  w.  j av a2 s .c o  m
 * 
 * @param httpBody
 * @return The data from the server as a string, in almost all cases JSON
 * @throws MalformedURLException
 * @throws IOException
 * @throws JSONException
 */
public static String getLoginResponse(Bundle httpBody) throws MalformedURLException, IOException {
    String response = "";
    URL url = new URL(WebServiceAuthProvider.tokenURL());
    trustAllHosts();
    HttpsURLConnection connection = createSecureConnection(url);
    connection.setHostnameVerifier(DO_NOT_VERIFY);
    String authString = "mobile_android:secret";
    String authValue = "Basic " + Base64.encodeToString(authString.getBytes(), Base64.NO_WRAP);

    connection.setRequestMethod("POST");
    connection.setRequestProperty("Authorization", authValue);
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.connect();

    OutputStream os = new BufferedOutputStream(connection.getOutputStream());
    os.write(encodePostBody(httpBody).getBytes());
    os.flush();
    try {
        LoggingUtils.d(LOG_TAG, connection.toString());
        response = readFromStream(connection.getInputStream());
    } catch (MalformedURLException e) {
        LoggingUtils.e(LOG_TAG,
                "Error reading stream \"" + connection.getInputStream() + "\". " + e.getLocalizedMessage(),
                null);
    } catch (IOException e) {
        response = readFromStream(connection.getErrorStream());
    } finally {
        connection.disconnect();
    }

    return response;
}