Example usage for javax.net.ssl HttpsURLConnection setDoOutput

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

Introduction

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

Prototype

public void setDoOutput(boolean dooutput) 

Source Link

Document

Sets the value of the doOutput field for this URLConnection to the specified value.

Usage

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

private boolean login() {
    String url = null;/*from   w w  w.  ja  v a  2s . 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:in.rab.ordboken.NeClient.java

private void loginMainSite() throws IOException, LoginException {
    ArrayList<BasicNameValuePair> data = new ArrayList<BasicNameValuePair>();

    data.add(new BasicNameValuePair("_save_loginForm", "true"));
    data.add(new BasicNameValuePair("redir", "/success"));
    data.add(new BasicNameValuePair("redirFail", "/fail"));
    data.add(new BasicNameValuePair("userName", mUsername));
    data.add(new BasicNameValuePair("passWord", mPassword));

    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(data);

    URL url = new URL("https://www.ne.se/user/login.jsp");
    HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
    https.setInstanceFollowRedirects(false);
    https.setFixedLengthStreamingMode((int) entity.getContentLength());
    https.setDoOutput(true);

    try {//from  w w  w.  ja v a2s.  c  o m
        OutputStream output = https.getOutputStream();
        entity.writeTo(output);
        output.close();

        Integer response = https.getResponseCode();
        if (response != 302) {
            throw new LoginException("Unexpected response: " + response);
        }

        String location = https.getHeaderField("Location");
        if (!location.contains("/success")) {
            throw new LoginException("Failed to login");
        }
    } finally {
        https.disconnect();
    }
}

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

/**
 * Post request./*from   w  w w . j  a  v a  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:httpRequests.GetPost.java

private void sendPost() throws Exception {

    String url = "https://selfsolve.apple.com/wcResults.do";
    URL obj = new URL(url);
    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

    //add reuqest header
    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", USER_AGENT);
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

    String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";

    // Send post request
    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParameters);//from   w  w w. j  ava 2s . c  o m
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'POST' request to URL : " + url);
    System.out.println("Post parameters : " + urlParameters);
    System.out.println("Response Code : " + responseCode);

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

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

    //print result
    System.out.println(response.toString());

}

From source file:org.wso2.carbon.appmgt.sampledeployer.http.HttpHandler.java

public String doPostHttps(String backEnd, String payload, String your_session_id, String contentType)
        throws IOException {
    URL obj = new URL(backEnd);

    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
    //add reuqest header
    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", USER_AGENT);
    if (!your_session_id.equals("")) {
        con.setRequestProperty("Cookie", "JSESSIONID=" + your_session_id);
    }//from ww w .  ja  va2s . com
    if (!contentType.equals("")) {
        con.setRequestProperty("Content-Type", contentType);
    }
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(payload);
    wr.flush();
    wr.close();
    int responseCode = con.getResponseCode();
    if (responseCode == 200) {
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        if (your_session_id.equals("")) {
            String session_id = response.substring((response.lastIndexOf(":") + 3),
                    (response.lastIndexOf("}") - 2));
            return session_id;
        } else if (your_session_id.equals("header")) {
            return con.getHeaderField("Set-Cookie");
        }

        return response.toString();
    }
    return null;
}

From source file:com.esri.geoevent.test.performance.bds.BdsEventConsumer.java

private int getMsLayerCount(String url) {
    int cnt = -1;

    try {// w ww  .  jav  a 2 s.  co m
        URL obj = new URL(url + "/query");
        HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

        //add request header
        con.setRequestMethod("POST");

        con.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
        con.setRequestProperty("Accept", "text/plain");

        String urlParameters = "where=" + URLEncoder.encode("1=1", "UTF-8") + "&returnCountOnly="
                + URLEncoder.encode("true", "UTF-8") + "&f=" + URLEncoder.encode("json", "UTF-8");

        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

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

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

        //print result
        String jsonString = response.toString();

        JSONTokener tokener = new JSONTokener(jsonString);

        JSONObject root = new JSONObject(tokener);

        cnt = root.getInt("count");

    } catch (Exception e) {
        cnt = -2;
    } finally {
        return cnt;
    }

}

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;// w  w  w .  ja v  a2s .  c om

    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;
}

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

private JablotronResponse sendUserCode(String code) {
    String url = null;/*  www .  ja  v  a  2s .co  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:com.esri.geoevent.test.tools.GetMapServiceCountRunnable.java

private int getMsLayerCount(String url) {
    int cnt = -1;

    try {//from w  ww  . j a v  a2 s. co  m
        URL obj = new URL(url + "/query");
        HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

        //add reuqest header
        con.setRequestMethod("POST");

        con.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
        con.setRequestProperty("Accept", "text/plain");

        String urlParameters = "where=" + URLEncoder.encode("1=1", "UTF-8") + "&returnCountOnly="
                + URLEncoder.encode("true", "UTF-8") + "&f=" + URLEncoder.encode("json", "UTF-8");

        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

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

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

        //print result
        String jsonString = response.toString();

        JSONTokener tokener = new JSONTokener(jsonString);

        JSONObject root = new JSONObject(tokener);

        cnt = root.getInt("count");

    } catch (Exception e) {
        cnt = -2;
    } finally {
        return cnt;
    }

}

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

private void login() {
    String url = null;//w ww .  j av a  2 s . com

    try {
        //login
        stavA = 0;
        stavB = 0;
        stavABC = 0;
        stavPGX = 0;
        stavPGY = 0;

        url = JABLOTRON_URL + "ajax/login.php";
        String urlParameters = "login=" + email + "&heslo=" + password + "&aStatus=200&loginType=Login";
        byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);

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

        synchronized (session) {
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Referer", JABLOTRON_URL);
            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);
            }

            JablotronResponse response = new JablotronResponse(connection);
            if (response.getException() != null) {
                logger.error("JablotronResponse login exception: {}", response.getException());
                return;
            }

            if (!response.isOKStatus())
                return;

            //get cookie
            session = response.getCookie();

            //cloud request

            url = JABLOTRON_URL + "ajax/widget-new.php?" + getBrowserTimestamp();
            ;
            cookieUrl = new URL(url);
            connection = (HttpsURLConnection) cookieUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Referer", JABLOTRON_URL + "cloud");
            connection.setRequestProperty("Cookie", session);
            connection.setRequestProperty("X-Requested-With", "XMLHttpRequest");
            setConnectionDefaults(connection);

            //line = readResponse(connection);
            response = new JablotronResponse(connection);

            if (response.getException() != null) {
                logger.error("JablotronResponse widget exception: {}", response.getException().toString());
                return;
            }

            if (response.getResponseCode() != 200 || !response.isOKStatus()) {
                return;
            }

            if (response.getWidgetsCount() == 0) {
                logger.error("Cannot found any jablotron device");
                return;
            }
            service = response.getServiceId(0);

            //service request
            url = response.getServiceUrl(0);
            if (!services.contains(service)) {
                services.add(service);
                logger.info("Found Jablotron service: {} id: {}", response.getServiceName(0), service);
            }
            cookieUrl = new URL(url);
            connection = (HttpsURLConnection) cookieUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Referer", JABLOTRON_URL);
            connection.setRequestProperty("Cookie", session);
            connection.setRequestProperty("Upgrade-Insecure-Requests", "1");
            setConnectionDefaults(connection);

            if (connection.getResponseCode() == 200) {
                logger.debug("Successfully logged to Jablotron cloud!");
            } else {
                logger.error("Cannot log in to Jablotron cloud!");
            }
        }

    } catch (MalformedURLException e) {
        logger.error("The URL '{}' is malformed: {}", url, e.toString());
    } catch (Exception e) {
        logger.error("Cannot get Jablotron login cookie: {}", e.toString());
    }
}