Example usage for javax.net.ssl HttpsURLConnection setRequestProperty

List of usage examples for javax.net.ssl HttpsURLConnection setRequestProperty

Introduction

In this page you can find the example usage for javax.net.ssl HttpsURLConnection setRequestProperty.

Prototype

public void setRequestProperty(String key, String value) 

Source Link

Document

Sets the general request property.

Usage

From source file:org.openhab.binding.jablotron.internal.JablotronBinding.java

private void logout() {

    String url = JABLOTRON_URL + "logout";
    try {/*  w ww  . j a va  2s.  com*/
        URL cookieUrl = new URL(url);

        HttpsURLConnection connection = (HttpsURLConnection) cookieUrl.openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Referer", JABLOTRON_URL + SERVICE_URL + service);
        connection.setRequestProperty("Cookie", session);
        connection.setRequestProperty("Upgrade-Insecure-Requests", "1");
        setConnectionDefaults(connection);

        JablotronResponse response = new JablotronResponse(connection);
    } catch (Exception e) {
        //Silence
        //logger.error(e.toString());
    } finally {
        controlDisabled = true;
        inService = false;
        session = "";
    }
    return;
}

From source file:org.openhab.binding.zonky.internal.ZonkyBinding.java

private Boolean refreshToken() {
    String url = null;//from   w  w  w.  java 2  s  . c  om

    try {
        //login
        url = ZONKY_URL + "oauth/token";
        String urlParameters = "refresh_token=" + refreshToken
                + "&grant_type=refresh_token&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();
        return true;

    } catch (MalformedURLException e) {
        logger.error("The URL '{}' is malformed", url, e);
    } catch (Exception e) {
        logger.error("Cannot get Zonky login token", e);
    }
    return false;
}

From source file:org.openhab.binding.zonky.internal.ZonkyBinding.java

private void login() {
    String url = null;/*from   ww w .  ja  v  a 2  s . c o m*/

    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:org.openhab.binding.jablotron.internal.JablotronBinding.java

private JablotronResponse sendGetStatusRequest() {

    String url = JABLOTRON_URL + "app/oasis/ajax/stav.php?" + getBrowserTimestamp();
    try {/*from w  w  w  .ja v a2  s. c o  m*/
        URL cookieUrl = new URL(url);

        synchronized (session) {
            HttpsURLConnection connection = (HttpsURLConnection) cookieUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Referer", JABLOTRON_URL + SERVICE_URL + service);
            connection.setRequestProperty("Cookie", session);
            connection.setRequestProperty("X-Requested-With", "XMLHttpRequest");
            setConnectionDefaults(connection);

            return new JablotronResponse(connection);
        }

    } catch (Exception e) {
        logger.error("sendGetStatusRequest exception: {}", e.toString());
        return new JablotronResponse(e);
    }
}

From source file:com.produban.cloudfoundry.bosh.bosh_javaclient.BoshClientImpl.java

/**
 * This method opens a {@link HttpsURLConnection} to the BOSH director using
 * the given path and sets up 'GET' method and authentication.
 *
 * @param path/*from   w  w  w  .  j  a v a  2s .com*/
 *            the path (starting with '/')
 * @return the {@link HttpsURLConnection} object
 * @throws MalformedURLException
 * @throws IOException
 * @throws ProtocolException
 * @throws UnsupportedEncodingException
 */
private HttpsURLConnection setupHttpsUrlConnection(String path)
        throws MalformedURLException, IOException, ProtocolException, UnsupportedEncodingException {
    URL requestURL = new URL("https://" + this.host + ":" + this.port + path);
    HttpsURLConnection httpsURLConnection = (HttpsURLConnection) requestURL.openConnection();
    httpsURLConnection.setRequestMethod("GET");
    httpsURLConnection.setUseCaches(false);

    String credentials = this.username + ":" + this.password;
    String basicAuthHeaderValue = "Basic " + Base64.encodeBase64String(credentials.getBytes("UTF-8"));
    httpsURLConnection.setRequestProperty("Authorization", basicAuthHeaderValue);
    httpsURLConnection.setDoInput(true);
    return httpsURLConnection;
}

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/*from w  w  w. ja v a  2  s. com*/
                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:org.openhab.binding.unifi.internal.UnifiBinding.java

private void logout() {
    URL url = null;//  w w  w  .j a  v  a  2 s .  com
    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:br.com.intelidev.dao.userDao.java

/**
  * Run the web service request/*from   ww w.j av  a  2 s . c  om*/
  * @param username
  * @param password
  * @return 
  */
public boolean login_acess(String username, String password) {
    HttpsURLConnection conn = null;
    boolean bo_return = false;

    try {
        // Create url to the Device Cloud server for a given web service request
        URL url = new URL("https://devicecloud.digi.com/ws/sci");
        conn = (HttpsURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod("GET");

        // Build authentication string
        String userpassword = username + ":" + password;

        // can change this to use a different base64 encoder
        String encodedAuthorization = Base64.encodeBase64String(userpassword.getBytes()).trim();

        // set request headers
        conn.setRequestProperty("Authorization", "Basic " + encodedAuthorization);
        // Get input stream from response and convert to String
        InputStream is = conn.getInputStream();

        Scanner isScanner = new Scanner(is);
        StringBuffer buf = new StringBuffer();
        while (isScanner.hasNextLine()) {
            buf.append(isScanner.nextLine() + "\n");
        }
        //String responseContent = buf.toString();

        // add line returns between tags to make it a bit more readable
        //responseContent = responseContent.replaceAll("><", ">\n<");

        // Output response to standard out
        //System.out.println(responseContent);
        bo_return = true;
    } catch (Exception e) {
        // Print any exceptions that occur
        System.out.println("br.com.intelidev.dao.userDao.login_acess() Error: " + e);
        bo_return = false;
        //e.printStackTrace();
    } finally {
        if (conn != null)
            conn.disconnect();
        if (bo_return) {
            System.out.println("Conectou ");
        } else {
            System.out.println("No conectou ");
        }

    }
    return bo_return;
}

From source file:pack_test.Get_stream.java

/**
 * Run the web service request//from www .  j  a  v a2 s. c  om
 */
//public static void main(String[] args) {
public void main() {
    HttpsURLConnection conn = null;

    try {
        // Create url to the Device Cloud server for a given web service request
        URL url = new URL(
                "https://devicecloud.digi.com/ws/v1/streams/history/00000000-00000000-00409DFF-FF6064F8/xbee.analog/[00:13:A2:00:40:E6:5A:88]!/AD1");
        conn = (HttpsURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod("GET");

        // Build authentication string
        String userpassword = username + ":" + password;

        // can change this to use a different base64 encoder
        String encodedAuthorization = Base64.encodeBase64String(userpassword.getBytes()).trim();

        // set request headers
        conn.setRequestProperty("Authorization", "Basic " + encodedAuthorization);
        // Get input stream from response and convert to String
        InputStream is = conn.getInputStream();

        Scanner isScanner = new Scanner(is);
        StringBuffer buf = new StringBuffer();
        while (isScanner.hasNextLine()) {
            buf.append(isScanner.nextLine() + "\n");
        }
        String responseContent = buf.toString();

        // add line returns between tags to make it a bit more readable
        responseContent = responseContent.replaceAll("><", ">\n<");

        // Output response to standard out
        System.out.println(responseContent);
    } catch (Exception e) {
        // Print any exceptions that occur
        e.printStackTrace();
    } finally {
        if (conn != null)
            conn.disconnect();
    }
}

From source file:com.dao.ShopThread.java

private HttpsURLConnection getHttpSConn(String payurl, String method, String strlength) throws Exception {
    // SSLContext??
    TrustManager[] tm = { new MyX509TrustManager() };
    SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
    sslContext.init(null, tm, new java.security.SecureRandom());
    // SSLContextSSLSocketFactory
    SSLSocketFactory ssf = sslContext.getSocketFactory();
    // Acts like a browser
    URL obj = new URL(payurl);
    HttpsURLConnection conn;
    conn = (HttpsURLConnection) obj.openConnection();
    conn.setSSLSocketFactory(ssf);// www  . jav a  2  s.co m
    conn.setRequestMethod(method);
    conn.setRequestProperty("Host", "mypay.5173.com");
    conn.setRequestProperty("User-Agent", USER_AGENT);
    conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
    conn.setRequestProperty("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3");
    conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    // conn.setRequestProperty("X-Requested-With", "XMLHttpRequest");
    conn.setRequestProperty("Referer", payurl);
    conn.setRequestProperty("Connection", "keep-alive");
    // conn.setRequestProperty("Pragma", "no-cache");
    // conn.setRequestProperty("Cache-Control", "no-cache");
    conn.setRequestProperty("Content-Length", strlength);
    conn.setDoOutput(true);
    conn.setDoInput(true);
    return conn;
}