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:pack_test.Get_stream.java

/**
 * Run the web service request/* w  w  w.  j  a  va  2  s .  c  o m*/
 */
//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:org.wso2.carbon.sample.service.EventsManagerService.java

public String performPostCall(String requestURL, Map<String, String> postDataParams)
        throws HttpException, IOException {

    URL url;//from   www. j  av a 2s. c o m
    String response = "";

    url = new URL(requestURL);

    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setReadTimeout(15000);
    conn.setConnectTimeout(15000);
    conn.setRequestMethod("POST");
    conn.setDoInput(true);
    conn.setDoOutput(true);

    OutputStream os = conn.getOutputStream();
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
    writer.write(getPostDataString(postDataParams));

    writer.flush();
    writer.close();
    os.close();
    int responseCode = conn.getResponseCode();

    if (responseCode == HttpsURLConnection.HTTP_OK) {
        String line;
        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        while ((line = br.readLine()) != null) {
            response += line;
        }
    } else {
        response = "";
        throw new HttpException(responseCode + "");
    }

    return response;
}

From source file:org.mule.modules.wechat.common.HttpsConnection.java

public Map<String, Object> post(String httpsURL, String json) throws Exception {
    // Setup connection
    String result = "";
    URL url = new URL(httpsURL);
    HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
    con.setRequestMethod("POST");
    con.setRequestProperty("Content-Type", "application/json; encoding=utf-8");
    con.setDoOutput(true);
    OutputStream ops = con.getOutputStream();
    ops.write(json.getBytes("UTF-8"));
    ops.flush();// ww w.  j a  v a2  s .  c om
    ops.close();

    // Call wechat
    InputStream ins = con.getInputStream();
    InputStreamReader isr = new InputStreamReader(ins, "UTF-8");
    BufferedReader in = new BufferedReader(isr);

    // Read result
    String inputLine;
    StringBuilder sb = new StringBuilder();
    while ((inputLine = in.readLine()) != null) {
        sb.append((new JSONObject(inputLine)).toString());
    }
    result = sb.toString();
    in.close();

    // Convert JSON string to Map
    ObjectMapper mapper = new ObjectMapper();
    Map<String, Object> map = mapper.readValue(result, new TypeReference<Map<String, Object>>() {
    });

    return map;
}

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

private void HttpPost(String AccessTokenUri, String apiKey) {
    InputStream inSt = null;//from w  w  w.  ja va  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:crossbear.convergence.ConvergenceConnector.java

/**
 * Contact a ConvergenceNotary and ask it for all information about certificate observations it has made on a specific host.
 * //www  .  j  a va 2 s  .  c  o  m
 * Please note: Contacting a ConvergenceNotary is possible with and without sending the fingerprint of the observed certificate. In both cases the Notary will send a list of
 * ConvergenceCertificateObservations. The problem is that if no fingerprint is sent or the fingerprint matches the last certificate that the Notary observed for the host, the Notary will just
 * read the list of ConvergenceCertificateObservations from its database. It will not contact the server to see if it the certificate is still the one it uses. The problem with that is that with
 * this algorithm Convergence usually makes only one certificate observation per server. When asked for that server a Notary will therefore reply "I saw that certificate last July". Since
 * Crossbear requires statements like "I saw this certificate since last July" it will send a fake-fingerprint to the Convergence Notaries. This compels the Notary to query the server for
 * its current certificate. After that the Notary will update its database and will then send the updated list of ConvergenceCertificateObservations to Crossbear.
 * 
 * @param notary
 *            The notary to contact
 * @param hostPort
 *            The Hostname and port of the server on which the information about the certificate observations is desired.
 * @return The Response-String that the Notary sent as an answer. It will contain a JSON-encoded list of ConvergenceCertificateObservations
 * @throws IOException
 * @throws KeyManagementException
 * @throws NoSuchAlgorithmException
 */
private static String contactNotary(ConvergenceNotary notary, String hostPort)
        throws IOException, KeyManagementException, NoSuchAlgorithmException {

    // Construct a fake fingerprint to send to the Notary (currently the Hex-String representation of "ConvergenceIsGreat:)")
    String data = "fingerprint=43:6F:6E:76:65:72:67:65:6E:63:65:49:73:47:72:65:61:74:3A:29";

    // Build the url to connect to based on the Notary and the certificate's host
    URL url = new URL("https://" + notary.getHostPort() + "/target/" + hostPort.replace(":", "+"));

    // Open a HttpsURLConnection for that url
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

    /*
     * Set a TrustManager on that connection that forces the use of the Notary's certificate. If the Notary sends any certificate that differs from the one that it is supposed to have (according
     * to the ConvergenceNotaries-table) an Exception will be thrown. This protects against Man-in-the-middle attacks placed between the Crossbear server and the Notary.
     */
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null,
            new TrustManager[] {
                    new TrustSingleCertificateTM(Message.hexStringToByteArray(notary.getCertSHA256Hash())) },
            new java.security.SecureRandom());
    conn.setSSLSocketFactory(sc.getSocketFactory());

    // Set the timeout during which the Notary has to reply
    conn.setConnectTimeout(3000);

    // POST the fake fingerprint to the Notary
    conn.setDoOutput(true);
    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    wr.write(data);
    wr.flush();

    // Get the Notary's response. Since Convergence replies with a 409-error if it has never observed a certificate conn.getInputStream() will be null. The way to get the Notarys reply in that case is to use conn.getErrorStream().
    InputStream is;
    if (conn.getResponseCode() >= 400) {
        is = conn.getErrorStream();

    } else {
        // This line should never be executed since we send a fake fingerprint that should never belong to an actually observed certificate. But who knows ...
        is = conn.getInputStream();
    }

    // Read the Notary's reply and store it
    String response = Message.inputStreamToString(is);

    // Close all opened streams
    wr.close();

    // Return the Notary's reply
    return response;

}

From source file:org.wso2.carbon.integration.common.tests.JaggeryServerTest.java

/**
 * Sending the request and getting the response
 * @param Uri - request url/*w ww.jav a2 s .  c o  m*/
 * @param append - append request parameters
 * @throws IOException
 */
private HttpsResponse getRequest(String Uri, String requestParameters, boolean append) throws IOException {
    if (Uri.startsWith("https://")) {
        String urlStr = Uri;
        if (requestParameters != null && requestParameters.length() > 0) {
            if (append) {
                urlStr += "?" + requestParameters;
            } else {
                urlStr += requestParameters;
            }
        }
        URL url = new URL(urlStr);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setDoOutput(true);
        conn.setHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        conn.setReadTimeout(30000);
        conn.connect();
        // Get the response
        StringBuilder sb = new StringBuilder();
        BufferedReader rd = null;
        try {
            rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
        } catch (FileNotFoundException ignored) {
        } catch (IOException ignored) {
        } finally {
            if (rd != null) {
                rd.close();
            }
            conn.disconnect();
        }
        return new HttpsResponse(sb.toString(), conn.getResponseCode());
    }
    return null;
}

From source file:org.belio.service.gateway.AirtelCharging.java

private String sendXmlOverPost(String url, String xml) {
    StringBuffer result = new StringBuffer();
    try {/*from  w  w w.jav  a2s  .  c  o m*/
        Launcher.LOG.info("======================xml==============");

        Launcher.LOG.info(xml.toString());

        //            String userPassword = "roamtech_KE:roamtech _KE!ibm123";
        //            URL url2 = new URL("https://41.223.58.133:8443/ChargingServiceFlowWeb/sca/ChargingExport1");

        String userPassword = "" + networkproperties.getProperty("air_info_u") + ":"
                + networkproperties.getProperty("air_info_p");
        URL url2 = new URL(url);

        // URLConnection urlc =  url.openConnection();
        URLConnection urlc = url2.openConnection();
        HttpsURLConnection conn = (HttpsURLConnection) urlc;
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("SOAPAction", "run");

        //            urlc.setDoOutput(true);
        //            urlc.setUseCaches(false);
        //            urlc.setAllowUserInteraction(false);
        conn.setRequestProperty("Authorization", "Basic " + new Base64().encode(userPassword.getBytes()));
        conn.setRequestProperty("Content-Type", "text/xml");

        conn.setHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });

        // Write post data
        DataOutputStream out = new DataOutputStream(conn.getOutputStream());
        out.writeBytes(xml);
        out.flush();
        out.close();
        BufferedReader aiResult = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        StringBuffer responseMessage = new StringBuffer();
        while ((line = aiResult.readLine()) != null) {
            responseMessage.append(line);
        }
        System.out.println(responseMessage);

        //urlc.s("POST");  
        //  urlc.setRequestProperty("SOAPAction", SOAP_ACTION);

        urlc.connect();

    }

    catch (MalformedURLException ex) {
        Logger.getLogger(AirtelCharging.class

                .getName()).log(Level.SEVERE, null, ex);
    }

    catch (IOException ex) {
        Logger.getLogger(AirtelCharging.class

                .getName()).log(Level.SEVERE, null, ex);
    }
    return result.toString();

    //        try {
    //            // String url = "https://selfsolve.apple.com/wcResults.do";
    //            HttpClient client = new DefaultHttpClient();
    //            HttpPost post = new HttpPost("https://41.223.58.133:8443/ChargingServiceFlowWeb/sca/ChargingExport1");
    //            // add header
    //            post.setHeader("User-Agent", USER_AGENT);
    //            post.setHeader("Content-type:", " text/xml");
    //            post.setHeader("charset", "utf-8");
    //            post.setHeader("Accept:", ",text/xml");
    //            post.setHeader("Cache-Control:", " no-cache");
    //            post.setHeader("Pragma:", " no-cache");
    //            post.setHeader("SOAPAction:", "run");
    //            post.setHeader("Content-length:", "xml");
    //            
    ////            String encoding = new Base64().encode((networkproperties.getProperty("air_charge_n") + ":"
    ////                    + networkproperties.getProperty("air_charge_p")).getBytes());
    //            String encoding = new Base64().encode( ("roamtech_KE:roamtech _KE!ibm123").getBytes());
    //            
    //            post.setHeader("Authorization", "Basic " + encoding);
    //
    //            // post.setHeader("Authorization: Basic ", "base64_encode(credentials)");
    //            List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
    //            
    //            urlParameters.add(new BasicNameValuePair("xml", xml));
    //            
    //            System.out.println("\n============================ : " + url);
    //
    ////            urlParameters.add(new BasicNameValuePair("srcCode", ""));
    ////            urlParameters.add(new BasicNameValuePair("phone", ""));
    ////            urlParameters.add(new BasicNameValuePair("contentId", ""));
    ////            urlParameters.add(new BasicNameValuePair("itemName", ""));
    ////            urlParameters.add(new BasicNameValuePair("contentDescription", ""));
    ////            urlParameters.add(new BasicNameValuePair("actualPrice", ""));
    ////            urlParameters.add(new BasicNameValuePair("contentMediaType", ""));
    ////            urlParameters.add(new BasicNameValuePair("contentUrl", ""));
    //            post.setEntity(new UrlEncodedFormEntity(urlParameters));
    //            
    //            HttpResponse response = client.execute(post);
    //            Launcher.LOG.info("\nSending 'POST' request to URL : " + url);
    //            Launcher.LOG.info("Post parameters : " + post.getEntity());
    //            Launcher.LOG.info("Response Code : "
    //                    + response.getStatusLine().getStatusCode());
    //            
    //            BufferedReader rd = new BufferedReader(
    //                    new InputStreamReader(response.getEntity().getContent()));
    //            
    //            String line = "";
    //            while ((line = rd.readLine()) != null) {
    //                result.append(line);
    //            }
    //            
    //            System.out.println(result.toString());
    //        } catch (UnsupportedEncodingException ex) {
    //            Launcher.LOG.info(ex.getMessage());
    //        } catch (IOException ex) {
    //            Launcher.LOG.info(ex.getMessage());
    //        }
}

From source file:de.thingweb.client.security.Security4NicePlugfest.java

public Registration requestRegistrationAS() throws IOException {
    String clientName = "opPostmanTestRS"; // CLIENT_NAME_PREFIX +
    // System.currentTimeMillis();
    String clientCredentials = "client_credentials";
    String requestBodyRegistration = "{\"client_name\": \"" + clientName + "\",\"grant_types\": [\""
            + clientCredentials + "\"], \"id_token_signed_response_alg\":\"" + "HS256" + "\"}";

    // Registration
    URL urlRegistration = new URL(HTTPS_PREFIX + HOST + REQUEST_REGISTRATION_AS);

    HttpsURLConnection httpConRegistration = (HttpsURLConnection) urlRegistration.openConnection();
    httpConRegistration.setDoOutput(true);
    httpConRegistration.setRequestProperty("Host", REQUEST_HEADER_HOST);
    httpConRegistration.setRequestProperty("Content-Type", "application/json");
    httpConRegistration.setRequestProperty("Accept", "application/json");
    httpConRegistration.setRequestMethod("POST");

    OutputStream outRegistration = httpConRegistration.getOutputStream();
    outRegistration.write(requestBodyRegistration.getBytes());
    outRegistration.close();/*w  ww. j  av a2  s  .co m*/

    int responseCodeRegistration = httpConRegistration.getResponseCode();
    log.info("responseCode Registration for " + urlRegistration + ": " + responseCodeRegistration);

    if (responseCodeRegistration == 201) {
        // everything ok
        InputStream isR = httpConRegistration.getInputStream();
        byte[] bisR = getBytesFromInputStream(isR);
        String jsonResponseRegistration = new String(bisR);
        log.info(jsonResponseRegistration);

        // extract the value of client_id (this value is called <c_id>in
        // the following) and the value of client_secret (called
        // <c_secret> in the following) from the JSON response

        ObjectMapper mapper = new ObjectMapper();
        JsonFactory factory = mapper.getFactory();
        JsonParser jp = factory.createParser(bisR);
        JsonNode actualObj = mapper.readTree(jp);

        JsonNode c_id = actualObj.get("client_id");
        JsonNode c_secret = actualObj.get("client_secret");

        if (c_id == null || c_id.getNodeType() != JsonNodeType.STRING || c_secret == null
                || c_secret.getNodeType() != JsonNodeType.STRING) {
            log.error("client_id: " + c_id);
            log.error("client_secret: " + c_secret);
        } else {
            // ok so far
            // Store <c_id> and <c_secret> for use during the token
            // acquisition
            log.info("client_id: " + c_id);
            log.info("client_secret: " + c_secret);

            return new Registration(c_id.textValue(), c_secret.textValue());
        }

    } else {
        // error
        InputStream error = httpConRegistration.getErrorStream();
        byte[] berror = getBytesFromInputStream(error);
        log.error(new String(berror));
    }
    httpConRegistration.disconnect();

    return null;
}

From source file:tetujin.nikeapi.core.JNikeLowLevelAPI.java

/**
 * /*from  ww w  .ja v a  2 s. c om*/
 * @param con ?HttpsURLConnection 
 * @return con option??HttpsURLConnection
 */
protected HttpsURLConnection setHttpHeader(HttpsURLConnection con) {
    try {
        con.setRequestMethod(this.method);
        con.setDoOutput(true);
        con.setInstanceFollowRedirects(false);
        con.setRequestProperty("Accept-Language", this.lang);
        con.setRequestProperty("Accept", this.accept);
        con.setRequestProperty("appid", this.appid);
        System.out.println("Accept: " + con.getRequestProperty("Accept"));
        System.out.println("appid: " + con.getRequestProperty("appid"));
        return con;
    } catch (ProtocolException e) {
        e.printStackTrace();
        return con;
    }
}

From source file:de.thingweb.client.security.Security4NicePlugfest.java

public Registration requestRegistrationAM() throws IOException {

    Registration registration = null;// w w  w.  ja v a  2 s .  c o m

    String clientName = CLIENT_NAME_PREFIX + System.currentTimeMillis();
    String clientCredentials = "client_credentials";
    String requestBodyRegistration = "{\"client_name\": \"" + clientName + "\",\"grant_types\": [\""
            + clientCredentials + "\"]}";

    // Registration
    URL urlRegistration = new URL(HTTPS_PREFIX + HOST + REQUEST_REGISTRATION_AM);

    HttpsURLConnection httpConRegistration = (HttpsURLConnection) urlRegistration.openConnection();
    httpConRegistration.setDoOutput(true);
    httpConRegistration.setRequestProperty("Host", REQUEST_HEADER_HOST);
    httpConRegistration.setRequestProperty("Content-Type", "application/json");
    httpConRegistration.setRequestProperty("Accept", "application/json");
    httpConRegistration.setRequestMethod("POST");

    OutputStream outRegistration = httpConRegistration.getOutputStream();
    outRegistration.write(requestBodyRegistration.getBytes());
    outRegistration.close();

    int responseCodeRegistration = httpConRegistration.getResponseCode();
    log.info("responseCode Registration for " + urlRegistration + ": " + responseCodeRegistration);

    if (responseCodeRegistration == 201) {
        // everything ok
        InputStream isR = httpConRegistration.getInputStream();
        byte[] bisR = getBytesFromInputStream(isR);
        String jsonResponseRegistration = new String(bisR);
        log.info(jsonResponseRegistration);

        // extract the value of client_id (this value is called <c_id>in
        // the following) and the value of client_secret (called
        // <c_secret> in the following) from the JSON response

        ObjectMapper mapper = new ObjectMapper();
        JsonFactory factory = mapper.getFactory();
        JsonParser jp = factory.createParser(bisR);
        JsonNode actualObj = mapper.readTree(jp);

        JsonNode c_id = actualObj.get("client_id");
        JsonNode c_secret = actualObj.get("client_secret");

        if (c_id == null || c_id.getNodeType() != JsonNodeType.STRING || c_secret == null
                || c_secret.getNodeType() != JsonNodeType.STRING) {
            log.error("client_id: " + c_id);
            log.error("client_secret: " + c_secret);
        } else {
            // ok so far
            // Store <c_id> and <c_secret> for use during the token
            // acquisition
            log.info("client_id: " + c_id);
            log.info("client_secret: " + c_secret);

            registration = new Registration(c_id.textValue(), c_secret.textValue());
        }

    } else {
        // error
        InputStream error = httpConRegistration.getErrorStream();
        byte[] berror = getBytesFromInputStream(error);
        log.error(new String(berror));
    }
    httpConRegistration.disconnect();

    return registration;
}