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.msopentech.thali.utilities.universal.test.ThaliTestUrlConnection.java

public static void TestThaliUrlConnection(String host, char[] passPhrase,
        CreateClientBuilder createClientBuilder, Context context)
        throws InterruptedException, UnrecoverableEntryException, KeyManagementException,
        NoSuchAlgorithmException, KeyStoreException, IOException {
    ThaliTestUtilities.configuringLoggingApacheClient();

    ThaliListener thaliTestServer = new ThaliListener();
    File keyStore = ThaliCryptoUtilities.getThaliKeyStoreFileObject(context.getFilesDir());

    // We want to start with a clean state
    if (keyStore.exists()) {
        keyStore.delete();/*from  www  . j av a 2  s  . co m*/
    }

    // We use a random port (e.g. port 0) both because it's good hygiene and because it keeps us from conflicting
    // with the 'real' Thali Device Hub if it's running.
    thaliTestServer.startServer(context, 0);

    int port = thaliTestServer.getSocketStatus().getPort();

    CouchDbInstance couchDbInstance = ThaliClientToDeviceHubUtilities
            .GetLocalCouchDbInstance(context.getFilesDir(), createClientBuilder, host, port, passPhrase);

    couchDbInstance.deleteDatabase(ThaliTestUtilities.TestDatabaseName);
    couchDbInstance.createDatabase(ThaliTestUtilities.TestDatabaseName);

    KeyStore clientKeyStore = ThaliCryptoUtilities.validateThaliKeyStore(context.getFilesDir());

    org.apache.http.client.HttpClient httpClientNoServerValidation = createClientBuilder
            .CreateApacheClient(host, port, null, clientKeyStore, passPhrase);

    PublicKey serverPublicKey = ThaliClientToDeviceHubUtilities
            .getServersRootPublicKey(httpClientNoServerValidation);

    String httpsURL = "https://" + host + ":" + port + "/" + ThaliTestUtilities.TestDatabaseName + "/";

    HttpsURLConnection httpsURLConnection = ThaliUrlConnection.getThaliUrlConnection(httpsURL, serverPublicKey,
            clientKeyStore, passPhrase);

    httpsURLConnection.setRequestMethod("GET");
    int responseCode = httpsURLConnection.getResponseCode();
    if (responseCode != 200) {
        throw new RuntimeException();
    }
}

From source file:org.openengsb.connector.facebook.internal.FacebookNotifier.java

private static String sendData(String httpsURL, String params) throws Exception {
    LOGGER.info("sending facebook-message");
    URL myurl = new URL(httpsURL);
    HttpsURLConnection con = (HttpsURLConnection) myurl.openConnection();
    if (params != null) {
        con.setDoOutput(true);/*from   ww  w  .j  a v a2  s .  c o  m*/
        con.setRequestMethod("POST");
        OutputStreamWriter ow = new OutputStreamWriter(con.getOutputStream());
        ow.write(params);
        ow.flush();
        ow.close();
    }
    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));

    StringBuffer output = new StringBuffer();
    String inputLine;

    while ((inputLine = in.readLine()) != null) {
        output.append(inputLine);
        LOGGER.debug(inputLine);
    }
    in.close();
    LOGGER.info("facebook message has been sent");
    return output.toString();
}

From source file:Main.java

private static String getData(String target, String method, String token) {
    try {/* ww  w  .  j  a  v  a2  s.c om*/
        URL url = new URL(target);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

        if (!TextUtils.isEmpty(token)) {
            conn.setRequestProperty("Authorization", token);
        }

        conn.setRequestMethod(method);
        conn.connect();

        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line, data = "";
        while ((line = in.readLine()) != null) {
            data += line;
        }
        in.close();

        return data;
    } catch (IOException ignored) {
        ignored.printStackTrace();
    }

    return null;
}

From source file:com.camel.trainreserve.JDKHttpsClient.java

private static HttpsURLConnection getConnection(URL url, String method, String ctype) throws IOException {
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setRequestMethod(method);
    conn.setDoInput(true);//  w  w  w .ja va2  s .com
    conn.setDoOutput(true);
    conn.setRequestProperty("Accept", "text/xml,text/javascript,text/html");
    conn.setRequestProperty("User-Agent", "stargate");
    conn.setRequestProperty("Content-Type", ctype);
    return conn;
}

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

static public String GetSystemInfo(String host, String token, long last_sample)
        throws JSONException, ParseException, IOException, AuthenticationException {
    try {//from ww  w . j a  v a  2  s.  c  om
        URL url = new URL("https://" + host + URL_SYSINFO + "/" + last_sample);
        Log.v(TAG, "GetSystemInfo: host: " + host + ", token: " + token + ", URL: " + url);

        HttpsURLConnection http = CreateConnection(url);

        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")) {
            Integer result = RESULT_UNKNOWN;
            try {
                result = Integer.valueOf(json_data.getString("result"));
            } catch (NumberFormatException e) {
            }

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

            if (result == RESULT_SUCCESS && json_data.has("data")) {
                //Log.i(TAG, "data: " + json_data.getString("data"));
                return json_data.getString("data");
            }

            if (result == RESULT_ACCESS_DENIED)
                throw new AuthenticationException();

            // New cookies?
            final String cookie = http.getHeaderField("Set-Cookie");
            if (cookie != null) {
                Log.d(TAG, "New cookie!");
            }

            // All other results are failures...
            throw new IOException();
        }
    } catch (MalformedURLException e) {
        Log.e(TAG, "MalformedURLException", e);
        throw new ParseException();
    }

    Log.i(TAG, "Malformed result");
    throw new IOException();
}

From source file:Main.java

public static String executeHttpsPost(String url, String data, InputStream key) {
    HttpsURLConnection localHttpsURLConnection = null;
    try {/*from   ww  w  . ja  v  a2s  .  c  om*/
        URL localURL = new URL(url);
        localHttpsURLConnection = (HttpsURLConnection) localURL.openConnection();
        localHttpsURLConnection.setRequestMethod("POST");
        localHttpsURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        localHttpsURLConnection.setRequestProperty("Content-Length",
                "" + Integer.toString(data.getBytes().length));
        localHttpsURLConnection.setRequestProperty("Content-Language", "en-US");

        localHttpsURLConnection.setUseCaches(false);
        localHttpsURLConnection.setDoInput(true);
        localHttpsURLConnection.setDoOutput(true);

        localHttpsURLConnection.connect();
        Certificate[] arrayOfCertificate = localHttpsURLConnection.getServerCertificates();

        byte[] arrayOfByte1 = new byte[294];
        DataInputStream localDataInputStream = new DataInputStream(key);
        localDataInputStream.readFully(arrayOfByte1);
        localDataInputStream.close();

        Certificate localCertificate = arrayOfCertificate[0];
        PublicKey localPublicKey = localCertificate.getPublicKey();
        byte[] arrayOfByte2 = localPublicKey.getEncoded();

        for (int i = 0; i < arrayOfByte2.length; i++) {
            if (arrayOfByte2[i] != arrayOfByte1[i])
                throw new RuntimeException("Public key mismatch");
        }

        DataOutputStream localDataOutputStream = new DataOutputStream(
                localHttpsURLConnection.getOutputStream());
        localDataOutputStream.writeBytes(data);
        localDataOutputStream.flush();
        localDataOutputStream.close();

        InputStream localInputStream = localHttpsURLConnection.getInputStream();
        BufferedReader localBufferedReader = new BufferedReader(new InputStreamReader(localInputStream));

        StringBuffer localStringBuffer = new StringBuffer();
        String str1;
        while ((str1 = localBufferedReader.readLine()) != null) {
            localStringBuffer.append(str1);
            localStringBuffer.append('\r');
        }
        localBufferedReader.close();

        return localStringBuffer.toString();
    } catch (Exception localException) {
        byte[] arrayOfByte1;
        localException.printStackTrace();
        return null;
    } finally {
        if (localHttpsURLConnection != null)
            localHttpsURLConnection.disconnect();
    }
}

From source file:org.schabi.newpipe.Downloader.java

/**Common functionality between download(String url) and download(String url, String language)*/
private static String dl(HttpsURLConnection con) throws IOException {
    StringBuilder response = new StringBuilder();

    try {//w  ww . ja va  2  s  .c om
        con.setRequestMethod("GET");
        con.setRequestProperty("User-Agent", USER_AGENT);

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;

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

    } catch (UnknownHostException uhe) {//thrown when there's no internet connection
        uhe.printStackTrace();
        //Toast.makeText(getActivity(), uhe.getMessage(), Toast.LENGTH_LONG).show();
    }

    return response.toString();
}

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

public static String fetchDataFromServer(final String url) throws IOException {
    LOGGER.warn("__ENTERING fetchDataFromServer()");

    final URL u = new URL(url);
    final HttpsURLConnection http = (HttpsURLConnection) u.openConnection();
    http.setRequestMethod(GET_STR);
    return fetchContent(http, 0);
}

From source file:com.ct855.util.HttpsClientUtil.java

public static String postUrl(String url, Map<String, String> params)
        throws IOException, NoSuchAlgorithmException, KeyManagementException, NoSuchProviderException {
    //SSLContext??
    TrustManager[] trustAllCerts = new TrustManager[] { new MyX509TrustManager() };
    SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
    sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

    //SSLContextSSLSocketFactory
    SSLSocketFactory ssf = sslContext.getSocketFactory();
    String data = "";
    for (String key : params.keySet()) {
        data += "&" + URLEncoder.encode(key, "UTF-8") + "=" + URLEncoder.encode(params.get(key), "UTF-8");
    }/*from  www.  j a  v a2s.  c  om*/
    data = data.substring(1);

    System.out.println("postUrl=>data:" + data);
    URL aURL = new java.net.URL(url);
    HttpsURLConnection aConnection = (HttpsURLConnection) aURL.openConnection();
    aConnection.setSSLSocketFactory(ssf);
    aConnection.setDoOutput(true);
    aConnection.setDoInput(true);
    aConnection.setRequestMethod("POST");
    OutputStreamWriter streamToAuthorize = new java.io.OutputStreamWriter(aConnection.getOutputStream());
    streamToAuthorize.write(data);
    streamToAuthorize.flush();
    streamToAuthorize.close();
    InputStream resultStream = aConnection.getInputStream();
    BufferedReader aReader = new java.io.BufferedReader(new java.io.InputStreamReader(resultStream));
    StringBuffer aResponse = new StringBuffer();
    String aLine = aReader.readLine();
    while (aLine != null) {
        aResponse.append(aLine + "\n");
        aLine = aReader.readLine();
    }
    resultStream.close();
    return aResponse.toString();
}

From source file:au.id.micolous.frogjump.Util.java

public static void updateCheck(final Activity activity) {
    (new AsyncTask<Void, Void, Boolean>() {
        @Override/*from   w  ww.j av  a 2  s  .co m*/
        protected Boolean doInBackground(Void... voids) {
            try {
                String my_version = Integer.toString(getVersionCode());
                URL url = new URL("https://micolous.github.io/frogjump/version.json");
                HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setDoInput(true);
                conn.setReadTimeout(10000);
                conn.setConnectTimeout(15000);
                conn.connect();

                int responseCode = conn.getResponseCode();
                if (responseCode == 200) {
                    InputStream is = conn.getInputStream();
                    byte[] buffer = new byte[1024];
                    if (is.read(buffer) == 0) {
                        Log.i(TAG, "Error reading update file, 0 bytes");
                        return false;
                    }
                    JSONObject root = (JSONObject) new JSONTokener(new String(buffer, "US-ASCII")).nextValue();

                    if (root.has(my_version)) {
                        if (root.getBoolean(my_version)) {
                            // Definitely needs update.
                            Log.i(TAG, "New version required, explicit flag.");
                            return true;
                        }
                    } else {
                        // unlisted version, assume it is old.
                        Log.i(TAG, "New version required, not in list.");
                        return true;
                    }

                }
            } catch (Exception ex) {
                Log.e(TAG, "Error getting update info", ex);
            }
            return false;
        }

        @Override
        protected void onPostExecute(Boolean needsUpdate) {
            if (needsUpdate)
                newVersionAlert(activity);
        }
    }).execute();
}