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.fastbootmobile.twofactorauthdemo.MainActivity.java

protected void registerWithBackend() {

    final SharedPreferences pref = this.getSharedPreferences(OwnPushClient.PREF_PUSH, Context.MODE_PRIVATE);

    Thread httpThread = new Thread(new Runnable() {

        private String TAG = "httpThread";
        private String ENDPOINT = "https://otp.demo.ownpush.com/push/register";

        @Override/*from w  w w.j  a va 2s.  com*/
        public void run() {
            URL urlObj;

            try {
                urlObj = new URL(ENDPOINT);

                String install_id = pref.getString(OwnPushClient.PREF_PUBLIC_KEY, null);

                if (install_id == null) {
                    return;
                }

                String mPostData = "push_id=" + install_id;
                HttpsURLConnection con = (HttpsURLConnection) urlObj.openConnection();

                con.setRequestProperty("User-Agent", "Mozilla/5.0 ( compatible ) ");
                con.setRequestProperty("Accept", "*/*");
                con.setDoInput(true);
                con.setRequestMethod("POST");
                con.getOutputStream().write(mPostData.getBytes());
                con.connect();
                int http_status = con.getResponseCode();

                if (http_status != 200) {
                    Log.e(TAG, "ERROR IN HTTP REPONSE : " + http_status);
                    return;
                }

                InputStream stream;
                stream = con.getInputStream();

                BufferedReader br = new BufferedReader(new InputStreamReader(stream));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line + "\n");
                }
                br.close();
                String data = sb.toString();

                if (data.contains("device_uid")) {
                    JSONObject json = new JSONObject(data);
                    String device_id = json.getString("device_uid");
                    pref.edit().putString("device_uid", device_id).commit();
                    Log.d(TAG, "GOT DEVICE UID OF " + device_id);

                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            updateUI();
                        }
                    });

                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

    httpThread.start();
}

From source file:net.roboconf.target.azure.internal.AzureIaasHandler.java

private int processPostRequest(URL url, byte[] data, String contentType, String keyStore,
        String keyStorePassword) throws GeneralSecurityException, IOException {

    SSLSocketFactory sslFactory = this.getSSLSocketFactory(keyStore, keyStorePassword);
    HttpsURLConnection con;
    con = (HttpsURLConnection) url.openConnection();
    con.setSSLSocketFactory(sslFactory);
    con.setDoOutput(true);/*from   w  w w. jav  a 2 s .co m*/
    con.setRequestMethod("POST");
    con.addRequestProperty("x-ms-version", "2014-04-01");
    con.setRequestProperty("Content-Length", String.valueOf(data.length));
    con.setRequestProperty("Content-Type", contentType);

    DataOutputStream requestStream = new DataOutputStream(con.getOutputStream());
    requestStream.write(data);
    requestStream.flush();
    requestStream.close();

    return con.getResponseCode();
}

From source file:com.github.abilityapi.abilityapi.external.Metrics.java

/**
 * Sends the data to the bStats server./*from   w  w w .j a v a  2  s .  c  om*/
 *
 * @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:org.kuali.mobility.push.service.send.AndroidSendService.java

/**
 * Creates a connection to the GCM server
 * @return The connection to the GCM server
 * @throws java.net.MalformedURLException
 * @throws java.io.IOException// ww  w.  j  ava  2  s .  c o m
 */
private HttpsURLConnection createConnection() throws IOException {
    HttpsURLConnection conn;
    //retrieve the connection from the pool.
    conn = (HttpsURLConnection) new URL(this.sendURL).openConnection();
    conn.setRequestMethod("POST");
    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setRequestProperty("Content-Type", "application/json");
    conn.setRequestProperty("Authorization", "key=" + this.auth);
    return conn;
}

From source file:org.wso2.carbon.identity.authenticator.smsotp.SMSOTPAuthenticator.java

/**
 * Send REST call//from  www . ja va2 s  . c  om
 */
public boolean sendRESTCall(String url, String urlParameters) throws IOException {
    HttpsURLConnection connection = null;
    try {
        URL smsProviderUrl = new URL(url + urlParameters);
        connection = (HttpsURLConnection) smsProviderUrl.openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod(SMSOTPConstants.HTTP_METHOD);
        if (connection.getResponseCode() == 200) {
            if (log.isDebugEnabled()) {
                log.debug("Code is successfully sent to your mobile number");
            }
            return true;
        }
        connection.disconnect();
    } catch (MalformedURLException e) {
        if (log.isDebugEnabled()) {
            log.error("Invalid URL", e);
        }
        throw new MalformedURLException();
    } catch (ProtocolException e) {
        if (log.isDebugEnabled()) {
            log.error("Error while setting the HTTP method", e);
        }
        throw new ProtocolException();
    } catch (IOException e) {
        if (log.isDebugEnabled()) {
            log.error("Error while getting the HTTP response", e);
        }
        throw new IOException();
    } finally {
        connection.disconnect();
    }
    return false;
}

From source file:org.disrupted.rumble.database.statistics.StatisticManager.java

public void onEventAsync(LinkLayerStarted event) {
    if (!event.linkLayerIdentifier.equals(WifiLinkLayerAdapter.LinkLayerIdentifier))
        return;//from w w w . j ava  2 s.  c  o m

    if (RumblePreferences.UserOkWithSharingAnonymousData(RumbleApplication.getContext())
            && RumblePreferences.isTimeToSync(RumbleApplication.getContext())) {
        if (!NetUtil.isURLReachable("http://disruptedsystems.org/"))
            return;

        try {
            // generate the JSON file
            byte[] json = generateStatJSON().toString().getBytes();

            // configure SSL
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            InputStream caInput = new BufferedInputStream(
                    RumbleApplication.getContext().getAssets().open("certs/disruptedsystemsCA.pem"));
            Certificate ca = cf.generateCertificate(caInput);

            String keyStoreType = KeyStore.getDefaultType();
            KeyStore keyStore = KeyStore.getInstance(keyStoreType);
            keyStore.load(null, null);
            keyStore.setCertificateEntry("ca", ca);

            String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
            tmf.init(keyStore);

            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, tmf.getTrustManagers(), null);

            URL url = new URL("https://data.disruptedsystems.org/post");
            HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
            urlConnection.setSSLSocketFactory(sslContext.getSocketFactory());

            // then configure the header
            urlConnection.setInstanceFollowRedirects(true);
            urlConnection.setRequestMethod("POST");
            urlConnection.setDoOutput(true);
            urlConnection.setRequestProperty("Content-Type", "application/json");
            urlConnection.setRequestProperty("Accept", "application/json");
            urlConnection.setRequestProperty("charset", "utf-8");
            urlConnection.setRequestProperty("Content-Length", Integer.toString(json.length));
            urlConnection.setUseCaches(false);

            // connect and send the JSON
            urlConnection.setConnectTimeout(10 * 1000);
            urlConnection.connect();
            urlConnection.getOutputStream().write(json);
            if (urlConnection.getResponseCode() != 200)
                throw new IOException("request failed");

            // erase the database
            RumblePreferences.updateLastSync(RumbleApplication.getContext());
            cleanDatabase();
        } catch (Exception ex) {
            Log.e(TAG, "Failed to establish SSL connection to server: " + ex.toString());
        }
    }
}

From source file:com.gmt2001.TwitchAPIv2.java

private JSONObject GetData(request_type type, String url, String post, String oauth) {
    JSONObject j = new JSONObject();

    try {/*from   w w  w  .j  av  a2 s .co  m*/
        URL u = new URL(url);
        HttpsURLConnection c = (HttpsURLConnection) u.openConnection();

        c.addRequestProperty("Accept", header_accept);

        if (!clientid.isEmpty()) {
            c.addRequestProperty("Client-ID", clientid);
        }

        if (!oauth.isEmpty()) {
            c.addRequestProperty("Authorization", "OAuth " + oauth);
        }

        c.setRequestMethod(type.name());

        c.setUseCaches(false);
        c.setDefaultUseCaches(false);
        c.setConnectTimeout(timeout);

        c.connect();

        if (!post.isEmpty()) {
            IOUtils.write(post, c.getOutputStream());
        }

        String content;

        if (c.getResponseCode() == 200) {
            content = IOUtils.toString(c.getInputStream(), c.getContentEncoding());
        } else {
            content = IOUtils.toString(c.getErrorStream(), c.getContentEncoding());
        }

        j = new JSONObject(content);
        j.put("_success", true);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", c.getResponseCode());
        j.put("_exception", "");
        j.put("_exceptionMessage", "");
    } catch (MalformedURLException ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_exception", "MalformedURLException");
        j.put("_exceptionMessage", ex.getMessage());
    } catch (SocketTimeoutException ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_exception", "SocketTimeoutException");
        j.put("_exceptionMessage", ex.getMessage());
    } catch (IOException ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_exception", "IOException");
        j.put("_exceptionMessage", ex.getMessage());
    } catch (Exception ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_exception", "Exception [" + ex.getClass().getName() + "]");
        j.put("_exceptionMessage", ex.getMessage());
    }

    return j;
}

From source file:com.github.opengarageapp.GarageToggleService.java

@Override
protected HttpsURLConnection getRequestFromIntent(String baseString, Intent intent)
        throws ClientProtocolException, IOException {
    HttpsURLConnection urlConnection = null;
    URL url = null;/* www  .  j av a 2s .c  o  m*/

    if (intent.getAction().equals(INTENT_TOGGLE1)) {
        url = new URL(baseString + "/doorCommand?door=1&command=Toggle");
        urlConnection = (HttpsURLConnection) url.openConnection();
    } else if (intent.getAction().equals(INTENT_CLOSE1)) {
        url = new URL(baseString + "/doorCommand?door=1&command=Toggle");
        urlConnection = (HttpsURLConnection) url.openConnection();
    } else {
        throw new IllegalArgumentException("Invalid action passed: " + intent.getAction());
    }
    urlConnection.setRequestMethod(HttpPost.METHOD_NAME);
    setupConnectionProperties(urlConnection);
    //urlConnection.setSSLSocketFactory(GarageSSLSocketFactory.getSSLSocketFactory(application));
    return urlConnection;
}

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

private void HttpPost(String AccessTokenUri, String apiKey) {
    InputStream inSt = null;/*from  www .j a  v  a  2s.c o m*/
    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:org.whispersystems.textsecure.push.PushServiceSocket.java

private void uploadExternalFile(String method, String url, byte[] data) throws IOException {
    URL uploadUrl = new URL(url);
    HttpsURLConnection connection = (HttpsURLConnection) uploadUrl.openConnection();
    connection.setDoOutput(true);/*from  w  w w . j  a  va2s.  c om*/
    connection.setRequestMethod(method);
    connection.setRequestProperty("Content-Type", "application/octet-stream");
    connection.connect();

    try {
        OutputStream out = connection.getOutputStream();
        out.write(data);
        out.close();

        if (connection.getResponseCode() != 200) {
            throw new IOException(
                    "Bad response: " + connection.getResponseCode() + " " + connection.getResponseMessage());
        }
    } finally {
        connection.disconnect();
    }
}