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:org.openhab.binding.unifi.internal.UnifiBinding.java

private String sendToController(String url, String urlParameters, String method) {
    try {/* w w w . j a v a  2s  .  co  m*/
        synchronized (cookies) {
            byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);

            URL cookieUrl = new URL(url);
            HttpsURLConnection connection = (HttpsURLConnection) cookieUrl.openConnection();

            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod(method);
            //for(String cookie : cookies) {
            connection.setRequestProperty("Cookie", cookies.get(0) + "; " + cookies.get(1));
            //}

            if (urlParameters.length() > 0) {
                connection.setDoOutput(true);
                connection.setRequestProperty("Content-Length", Integer.toString(postData.length));
                connection.setUseCaches(false);

                try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
                    wr.write(postData);
                }
            }

            InputStream response = connection.getInputStream();
            String line = readResponse(response);
            if (!checkResponse(line)) {
                logger.error("Unifi response: " + line);

            }
            return line;
        }
    } catch (MalformedURLException e) {
        logger.error("The URL '" + url + "' is malformed: " + e.toString());
    } catch (Exception e) {
        logger.error("Cannot send data " + urlParameters + " to url " + url + ". Exception: " + e.toString());
    }
    return "";
}

From source file:com.adobe.ibm.watson.traits.impl.WatsonServiceClient.java

/**
 * Fetches the IBM Watson Personal Insights report using the user's Twitter Timeline.
 * @param language//from  w  ww.j  a v  a2  s  .  c  o  m
 * @param tweets
 * @param resource
 * @return
 * @throws Exception
 */
public String getWatsonScore(String language, String tweets, Resource resource) throws Exception {

    HttpsURLConnection connection = null;

    // Check if the username and password have been injected to the service.
    // If not, extract them from the cloud service configuration attached to the page.
    if (this.username == null || this.password == null) {
        getWatsonCloudSettings(resource);
    }

    // Build the request to IBM Watson.
    log.info("The Base Url is: " + this.baseUrl);
    String encodedCreds = getBasicAuthenticationEncoding();
    URL url = new URL(this.baseUrl + "/v2/profile");

    connection = (HttpsURLConnection) url.openConnection();
    connection.setRequestMethod("POST");
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setRequestProperty("Accept", "application/json");
    connection.setRequestProperty("Content-Language", language);
    connection.setRequestProperty("Accept-Language", "en-us");
    connection.setRequestProperty("Content-Type", ContentType.TEXT_PLAIN.toString());
    connection.setRequestProperty("Authorization", "Basic " + encodedCreds);
    connection.setUseCaches(false);
    connection.getOutputStream().write(tweets.getBytes());
    connection.getOutputStream().flush();
    connection.connect();

    log.info("Parsing response from Watson");
    StringBuilder str = new StringBuilder();

    BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String line = "";
    while ((line = br.readLine()) != null) {
        str.append(line + System.getProperty("line.separator"));
    }

    if (connection.getResponseCode() != 200) {
        // The call failed, throw an exception.
        log.error(connection.getResponseCode() + " : " + connection.getResponseMessage());
        connection.disconnect();
        throw new Exception("IBM Watson Server responded with an error: " + connection.getResponseMessage());
    } else {
        connection.disconnect();
        return str.toString();
    }
}

From source file:tangocard.sdk.service.ServiceProxy.java

/**
 * Post request.//www.  j  ava  2s .c  om
 *
 * @return true, if successful
 * @throws Exception the exception
 */
protected String postRequest() throws Exception {
    if (null == this._path) {
        throw new TangoCardSdkException("Member variable '_path' is null.");
    }

    String responseJsonEncoded = null;
    URL url = null;
    HttpsURLConnection connection = null;

    try {
        url = new URL(this._path);
    } catch (MalformedURLException e) {
        throw new TangoCardSdkException("MalformedURLException", e);
    }

    if (this.mapRequest()) {
        try {
            // connect to the server over HTTPS and submit the payload
            connection = (HttpsURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-length", String.valueOf(this._str_request_json.length()));
            connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");

            // open up the output stream of the connection
            DataOutputStream output = new DataOutputStream(connection.getOutputStream());
            output.write(this._str_request_json.getBytes());
        } catch (Exception e) {
            throw new TangoCardSdkException(String.format("Problems executing request: %s: '%s'",
                    e.getClass().toString(), e.getMessage()), e);
        }

        try {
            // now read the input stream until it is closed, line by line adding to the response
            InputStream inputstream = connection.getInputStream();
            InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
            BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
            StringBuffer response = new StringBuffer();
            String line = null;
            while ((line = bufferedreader.readLine()) != null) {
                response.append(line);
            }

            responseJsonEncoded = response.toString();
        } catch (Exception e) {
            throw new TangoCardSdkException(String.format("Problems reading response: %s: '%s'",
                    e.getClass().toString(), e.getMessage()), e);
        }
    }

    return responseJsonEncoded;
}

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);//from   w w w  .  j  a  va 2  s . c  o 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;
}

From source file:com.dao.ShopThread.java

private HttpsURLConnection getHttpSConn(String httpsurl) 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(httpsurl);
    HttpsURLConnection conn;
    conn = (HttpsURLConnection) obj.openConnection();
    conn.setSSLSocketFactory(ssf);/*from ww w.  ja  v a 2  s  .co m*/
    conn.setRequestMethod("GET");
    if (null != this.cookies) {
        conn.addRequestProperty("Cookie", GenericUtil.cookieFormat(this.cookies));
    }
    conn.setRequestProperty("Host", "security.5173.com");
    conn.setRequestProperty("User-Agent", USER_AGENT);
    conn.setRequestProperty("Accept", "*/*");
    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; charset=UTF-8");
    conn.setRequestProperty("Connection", "keep-alive");
    conn.setRequestProperty("Pragma", "no-cache");
    conn.setRequestProperty("Cache-Control", "no-cache");
    conn.setDoOutput(true);
    conn.setDoInput(true);
    return conn;
}

From source file:com.carvoyant.modularinput.Program.java

private JSONObject getRefreshToken(EventWriter ew, String clientId, String clientSecret, String refreshToken) {
    JSONObject tokenJson = null;//from  w  ww . jav a 2  s .c o  m
    HttpsURLConnection getTokenConnection = null;

    try {
        BufferedReader tokenResponseReader = null;
        URL url = new URL("https://api.carvoyant.com/oauth/token");
        //         URL url = new URL("https://sandbox-api.carvoyant.com/sandbox/oauth/token");
        getTokenConnection = (HttpsURLConnection) url.openConnection();
        getTokenConnection.setReadTimeout(30000);
        getTokenConnection.setConnectTimeout(30000);
        getTokenConnection.setRequestMethod("POST");
        getTokenConnection.setDoInput(true);
        getTokenConnection.setDoOutput(true);

        List<SimpleEntry> getTokenParams = new ArrayList<SimpleEntry>();
        getTokenParams.add(new SimpleEntry("client_id", clientId));
        getTokenParams.add(new SimpleEntry("client_secret", clientSecret));
        getTokenParams.add(new SimpleEntry("grant_type", "refresh_token"));
        getTokenParams.add(new SimpleEntry("refresh_token", refreshToken));

        String userpass = clientId + ":" + clientSecret;
        String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes());

        getTokenConnection.setRequestProperty("Authorization", basicAuth);

        OutputStream os = getTokenConnection.getOutputStream();
        os.write(getQuery(getTokenParams).getBytes("UTF-8"));
        os.close();

        if (getTokenConnection.getResponseCode() < 400) {
            tokenResponseReader = new BufferedReader(
                    new InputStreamReader(getTokenConnection.getInputStream()));
            String inputLine;
            StringBuffer sb = new StringBuffer();
            while ((inputLine = tokenResponseReader.readLine()) != null) {
                sb.append(inputLine);
            }

            tokenJson = new JSONObject(sb.toString());
            ew.synchronizedLog(EventWriter.INFO, "Refreshed Carvoyant access token.");
        } else {
            tokenResponseReader = new BufferedReader(
                    new InputStreamReader(getTokenConnection.getErrorStream()));
            StringBuffer sb = new StringBuffer();
            String inputLine;
            while ((inputLine = tokenResponseReader.readLine()) != null) {
                sb.append(inputLine);
            }
            ew.synchronizedLog(EventWriter.ERROR, "Carvoyant Refresh Token Error. CLIENT_ID:" + clientId
                    + ", REFRESH_TOKEN:" + refreshToken + ",ERROR_MSG: " + sb.toString());
        }

        getTokenConnection.disconnect();
    } catch (MalformedURLException mue) {
        ew.synchronizedLog(EventWriter.ERROR, "Carvoyant Refresh Token Error: " + mue.getMessage());
    } catch (IOException ioe) {
        ew.synchronizedLog(EventWriter.ERROR, "Carvoyant Refresh Token Error: " + ioe.getMessage());
    } finally {
        if (null != getTokenConnection) {
            getTokenConnection.disconnect();
        }
    }

    return tokenJson;
}

From source file:org.openhab.binding.unifi.internal.UnifiBinding.java

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

    try {
        url = getControllerUrl("api/login");
        String urlParameters = "{'username':'" + username + "','password':'" + password + "'}";
        byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);

        URL cookieUrl = new URL(url);
        HttpsURLConnection connection = (HttpsURLConnection) cookieUrl.openConnection();
        connection.setDoOutput(true);
        connection.setInstanceFollowRedirects(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Referer", getControllerUrl("login"));
        connection.setRequestProperty("Content-Length", Integer.toString(postData.length));
        connection.setUseCaches(false);

        try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
            wr.write(postData);
        }

        //get cookie
        cookies.clear();
        String headerName;
        for (int i = 1; (headerName = connection.getHeaderFieldKey(i)) != null; i++) {
            if (headerName.equals("Set-Cookie")) {
                cookies.add(connection.getHeaderField(i));
            }
        }

        InputStream response = connection.getInputStream();
        String line = readResponse(response);
        logger.debug("Unifi response: " + line);
        return checkResponse(line);

    } catch (MalformedURLException e) {
        logger.error("The URL '" + url + "' is malformed: " + e.toString());
    } catch (Exception e) {
        logger.error("Cannot get Ubiquiti Unifi login cookie: " + e.toString());
    }
    return false;
}

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

private JablotronResponse sendUserCode(String code) {
    String url = null;/*from  ww w . j a v a  2  s  .  c  o m*/

    try {
        url = JABLOTRON_URL + "app/oasis/ajax/ovladani.php";
        String urlParameters = "section=STATE&status=" + ((code.isEmpty()) ? "1" : "") + "&code=" + code;
        byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);

        URL cookieUrl = new URL(url);
        HttpsURLConnection connection = (HttpsURLConnection) cookieUrl.openConnection();
        JablotronResponse response;

        synchronized (session) {
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Referer", JABLOTRON_URL + SERVICE_URL + service);
            connection.setRequestProperty("Cookie", session);
            connection.setRequestProperty("Content-Length", Integer.toString(postData.length));
            connection.setRequestProperty("X-Requested-With", "XMLHttpRequest");
            setConnectionDefaults(connection);
            try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
                wr.write(postData);
            }
            response = new JablotronResponse(connection);
        }
        logger.debug("sendUserCode response: {}", response.getResponse());
        return response;
    } catch (Exception ex) {
        logger.error("sendUserCode exception: {}", ex.toString());
    }
    return null;
}

From source file:br.com.intelidev.dao.DadosDao.java

public List<Dados> get_stream_data(String stream_api, String user, String pass) {

    HttpsURLConnection conn = null;
    List<Dados> list_return = new ArrayList<>();
    int i;/*ww w. j  ava2 s .  co  m*/

    try {
        // Create url to the Device Cloud server for a given web service request
        //00000000-00000000-00409DFF-FF6064F8/xbee.analog/[00:13:A2:00:40:E6:5A:88]!/AD1
        ObjectMapper mapper = new ObjectMapper();
        URL url = new URL("https://devicecloud.digi.com/ws/v1/streams/history/" + stream_api);
        //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 = user + ":" + pass;
        System.out.println(userpassword);

        // 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);
        // Convert JSON string to Object
        StreamDados stream = mapper.readValue(responseContent, StreamDados.class);
        //System.out.println(stream.getList());
        System.out.println(stream.getList().size());
        for (i = 0; i < stream.getList().size(); i++) {
            list_return.add(stream.getList().get(i));
            //System.out.println("ts: "+ stream.getList().get(i).getTimestamp() + "Value: " + stream.getList().get(i).getValue());

        }

    } catch (Exception e) {
        // Print any exceptions that occur
        System.out.println("br.com.intelidev.dao.DadosDao.get_stream_data() e" + e);
    } finally {
        if (conn != null)
            conn.disconnect();
    }

    return list_return;
}