Example usage for java.io DataOutputStream writeBytes

List of usage examples for java.io DataOutputStream writeBytes

Introduction

In this page you can find the example usage for java.io DataOutputStream writeBytes.

Prototype

public final void writeBytes(String s) throws IOException 

Source Link

Document

Writes out the string to the underlying output stream as a sequence of bytes.

Usage

From source file:org.openhab.binding.whistle.internal.WhistleBinding.java

protected static String getAuthToken(String username, String password) throws Exception {
    logger.debug("Using username: '{}' / password: '{}'", username, password);

    URL obj = new URL(APIROOT + "tokens.json");
    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
    // add request headers and parameters
    con.setDoOutput(true);//w w  w  .  j  a  va 2  s . c  om
    con.setRequestProperty("Content-Type", "application/json");
    con.setRequestProperty("User-Agent", "WhistleApp/102 (iPhone; iOS 7.0.4; Scale/2.00)");
    con.setRequestMethod("POST");
    String urlParameters = "{\"password\":\"" + password + "\",\"email\":\"" + username
            + "\",\"app_id\":\"com.whistle.WhistleApp\"}";
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.flush();
    wr.close();
    if (con.getResponseCode() != 200) {
        logger.error("Username / password combination didn't work. Failed to get AuthenticationToken");
        return null;
    }
    // Read the buffer
    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String response = in.readLine();
    in.close();
    // Parse the data and return the token
    JsonObject jobj = new Gson().fromJson(response, JsonObject.class);
    return jobj.get("token").getAsString();
}

From source file:org.forgerock.openam.doc.jwt.bearer.Main.java

private static String authenticate(String username, String password) throws Exception {

    System.out.println("Authenticating as user:" + username + ";endpoint:" + authnEndpoint);
    URL authn = new URL(authnEndpoint);
    HttpURLConnection connection = (HttpURLConnection) authn.openConnection();

    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "application/json");
    connection.setRequestProperty("X-OpenAM-Username", username);
    connection.setRequestProperty("X-OpenAM-Password", password);
    connection.setDoOutput(true);/*from  ww w  . j  a  va 2  s . c om*/

    /*  $ curl \
      --request POST \
      --header "Content-Type: application/json" \
      --header "X-OpenAM-Username: demo" \
      --header "X-OpenAM-Password: changeit" \
      https://openam.example.com:8443/openam/json/authenticate */

    DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream());
    dataOutputStream.writeBytes("{}");
    dataOutputStream.flush();
    dataOutputStream.close();

    int responseCode = connection.getResponseCode();

    BufferedReader input;
    if (responseCode == 200) {
        input = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    } else {
        input = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
    }

    //Need to parse json response
    StringBuilder response = new StringBuilder();
    if (input != null) {
        String line;
        while ((line = input.readLine()) != null) {
            response.append(line);
        }
        input.close();
    } else {
        response.append("No input stream from reader.");
    }
    String tokenID = parseTokenId(response.toString());

    System.out.println("Response code: " + responseCode);
    return tokenID;

}

From source file:com.microsoft.office365.msgraphsnippetapp.SnippetsUnitTests.java

@BeforeClass
public static void getAccessTokenUsingPasswordGrant()
        throws IOException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException, JSONException {
    URL url = new URL(TOKEN_ENDPOINT);
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();

    String urlParameters = String.format(
            "grant_type=%1$s&resource=%2$s&client_id=%3$s&username=%4$s&password=%5$s", GRANT_TYPE,
            URLEncoder.encode(ServiceConstants.AUTHENTICATION_RESOURCE_ID, "UTF-8"), clientId, username,
            password);/*from  w ww  .j a  v  a2 s .c  o m*/

    connection.setRequestMethod(REQUEST_METHOD);
    connection.setRequestProperty("Content-Type", CONTENT_TYPE);
    connection.setRequestProperty("Content-Length", String.valueOf(urlParameters.getBytes("UTF-8").length));

    connection.setDoOutput(true);
    DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream());
    dataOutputStream.writeBytes(urlParameters);
    dataOutputStream.flush();
    dataOutputStream.close();

    connection.getResponseCode();

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

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

    JsonParser jsonParser = new JsonParser();
    JsonObject grantResponse = (JsonObject) jsonParser.parse(response.toString());
    accessToken = grantResponse.get("access_token").getAsString();

    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    logging.setLevel(HttpLoggingInterceptor.Level.BODY);

    OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            request = request.newBuilder().addHeader("Authorization", "Bearer " + accessToken)
                    // This header has been added to identify this sample in the Microsoft Graph service.
                    // If you're using this code for your project please remove the following line.
                    .addHeader("SampleID", "android-java-snippets-rest-sample").build();

            return chain.proceed(request);
        }
    }).addInterceptor(logging).build();

    Retrofit retrofit = new Retrofit.Builder().baseUrl(ServiceConstants.AUTHENTICATION_RESOURCE_ID)
            .client(client).addConverterFactory(GsonConverterFactory.create()).build();

    contactService = retrofit.create(MSGraphContactService.class);
    drivesService = retrofit.create(MSGraphDrivesService.class);
    eventsService = retrofit.create(MSGraphEventsService.class);
    groupsService = retrofit.create(MSGraphGroupsService.class);
    mailService = retrofit.create(MSGraphMailService.class);
    meService = retrofit.create(MSGraphMeService.class);
    userService = retrofit.create(MSGraphUserService.class);

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss", Locale.US);
    dateTime = simpleDateFormat.format(new Date());
}

From source file:org.runnerup.export.FormCrawler.java

public static void postMulti(HttpURLConnection conn, Part<?> parts[]) throws IOException {
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****" + Long.toString(System.currentTimeMillis()) + "*****";
    conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
    DataOutputStream outputStream = new DataOutputStream(conn.getOutputStream());
    for (Part<?> part : parts) {
        outputStream.writeBytes(twoHyphens + boundary + lineEnd);
        outputStream.writeBytes("Content-Disposition: form-data; name=\"" + part.name + "\"");
        if (part.filename != null)
            outputStream.writeBytes("; filename=\"" + part.filename + "\"");
        outputStream.writeBytes(lineEnd);

        if (part.contentType != null)
            outputStream.writeBytes("Content-Type: " + part.contentType + lineEnd);
        if (part.contentTransferEncoding != null)
            outputStream.writeBytes("Content-Transfer-Encoding: " + part.contentTransferEncoding + lineEnd);
        outputStream.writeBytes(lineEnd);
        part.value.write(outputStream);/*  w  ww  .  java 2 s  . c om*/
        outputStream.writeBytes(lineEnd);
    }
    outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
    outputStream.flush();
    outputStream.close();
}

From source file:gov.nasa.arc.geocam.geocam.HttpPost.java

protected static void assembleMultipart(DataOutputStream out, Map<String, String> vars, String fileKey,
        String fileName, InputStream istream) throws IOException {

    for (String key : vars.keySet()) {
        out.writeBytes("--" + BOUNDARY + CRLF);
        out.writeBytes("Content-Disposition: form-data; name=\"" + key + "\"" + CRLF);
        out.writeBytes(CRLF);/*from ww w . ja  va  2 s.c om*/
        out.writeBytes(vars.get(key) + CRLF);
    }

    out.writeBytes("--" + BOUNDARY + CRLF);
    out.writeBytes(
            "Content-Disposition: form-data; name=\"" + fileKey + "\"; filename=\"" + fileName + "\"" + CRLF);
    out.writeBytes("Content-Type: application/octet-stream" + CRLF);
    out.writeBytes(CRLF);

    // write stream
    //http://getablogger.blogspot.com/2008/01/android-how-to-post-file-to-php-server.html
    int maxBufferSize = 1024;
    int bytesAvailable = istream.available();
    int bufferSize = Math.min(maxBufferSize, bytesAvailable);
    byte[] buffer = new byte[bufferSize];

    int bytesRead = istream.read(buffer, 0, bufferSize);
    while (bytesRead > 0) {
        out.write(buffer, 0, bufferSize);
        out.flush();
        bytesAvailable = istream.available();
        bufferSize = Math.min(maxBufferSize, bytesAvailable);
        bytesRead = istream.read(buffer, 0, bufferSize);
    }

    out.writeBytes(CRLF);
    out.writeBytes("--" + BOUNDARY + "--" + CRLF);
    out.writeBytes(CRLF);
}

From source file:org.spoutcraft.launcher.util.Utils.java

public static String executePost(String targetURL, String urlParameters, JProgressBar progress)
        throws PermissionDeniedException {
    URLConnection connection = null;
    try {//  w  w w . j  ava 2s. c  om
        URL url = new URL(targetURL);
        connection = url.openConnection();
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        connection.setRequestProperty("Content-Length", Integer.toString(urlParameters.getBytes().length));
        connection.setRequestProperty("Content-Language", "en-US");

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

        connection.setConnectTimeout(10000);

        connection.connect();

        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

        InputStream is = connection.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));

        StringBuilder response = new StringBuilder();
        String line;
        while ((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\r');
        }
        rd.close();

        return response.toString();
    } catch (SocketException e) {
        if (e.getMessage().equalsIgnoreCase("Permission denied: connect")) {
            throw new PermissionDeniedException("Permission to login was denied");
        }
    } catch (Exception e) {
        String message = "Login failed...";
        progress.setString(message);
    }
    return null;
}

From source file:org.transitime.custom.missionBay.SfmtaApiCaller.java

/**
 * Posts the JSON string to the URL. For either the telemetry or the stop
 * command./*from  w w  w .jav a2s.com*/
 * 
 * @param baseUrl
 * @param jsonStr
 * @return True if successfully posted the data
 */
private static boolean post(String baseUrl, String jsonStr) {
    try {
        // Create the connection
        URL url = new URL(baseUrl);
        HttpsURLConnection con = (HttpsURLConnection) url.openConnection();

        // Set parameters for the connection
        con.setRequestMethod("POST");
        con.setRequestProperty("content-type", "application/json");
        con.setDoOutput(true);
        con.setDoInput(true);
        con.setUseCaches(false);

        // API now uses basic authentication
        String authString = login.getValue() + ":" + password.getValue();
        byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
        String authStringEnc = new String(authEncBytes);
        con.setRequestProperty("Authorization", "Basic " + authStringEnc);

        // Set the timeout so don't wait forever (unless timeout is set to 0)
        int timeoutMsec = timeout.getValue();
        con.setConnectTimeout(timeoutMsec);
        con.setReadTimeout(timeoutMsec);

        // Write the json data to the connection
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(jsonStr);
        wr.flush();
        wr.close();

        // Get the response
        int responseCode = con.getResponseCode();

        // If wasn't successful then log the response so can debug
        if (responseCode != 200) {
            String responseStr = "";
            if (responseCode != 500) {
                // Response code indicates there was a problem so get the
                // reply in case API returned useful error message
                InputStream inputStream = con.getErrorStream();
                if (inputStream != null) {
                    BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
                    String inputLine;
                    StringBuffer response = new StringBuffer();
                    while ((inputLine = in.readLine()) != null) {
                        response.append(inputLine);
                    }
                    in.close();
                    responseStr = response.toString();
                }
            }

            // Lot that response code indicates there was a problem
            logger.error(
                    "Bad HTTP response {} when writing data to SFMTA "
                            + "API. Response text=\"{}\" URL={} json=\n{}",
                    responseCode, responseStr, baseUrl, jsonStr);
        }

        // Done so disconnect just for the heck of it
        con.disconnect();

        // Return whether was successful
        return responseCode == 200;
    } catch (IOException e) {
        logger.error("Exception when writing data to SFMTA API: \"{}\" " + "URL={} json=\n{}", e.getMessage(),
                baseUrl, jsonStr);

        // Return that was unsuccessful
        return false;
    }

}

From source file:fr.zcraft.zbanque.network.PacketSender.java

private static HTTPResponse makeRequest(String url, PacketPlayOut.PacketType method, String data)
        throws Throwable {
    // ***  REQUEST  ***

    final URL urlObj = new URL(url);
    final HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection();

    connection.setRequestMethod(method.name());
    connection.setRequestProperty("User-Agent", USER_AGENT);

    authenticateRequest(connection);//from w  w w.  j a  va2 s  .  co m

    connection.setDoOutput(true);

    try {
        try {
            connection.connect();
        } catch (IOException ignored) {
        }

        if (method == PacketPlayOut.PacketType.POST) {
            DataOutputStream out = null;
            try {
                out = new DataOutputStream(connection.getOutputStream());
                if (data != null)
                    out.writeBytes(data);
                out.flush();
            } finally {
                if (out != null)
                    out.close();
            }
        }

        // ***  RESPONSE  ***

        int responseCode;
        boolean failed = false;

        try {
            responseCode = connection.getResponseCode();
        } catch (IOException e) {
            // HttpUrlConnection will throw an IOException if any 4XX
            // response is sent. If we request the status again, this
            // time the internal status will be properly set, and we'll be
            // able to retrieve it.
            // Thanks to Iigo.
            responseCode = connection.getResponseCode();
            failed = true;
        }

        BufferedReader in = null;
        String body = "";
        try {
            InputStream stream;
            try {
                stream = connection.getInputStream();
            } catch (IOException e) {
                // Same as before
                stream = connection.getErrorStream();
                failed = true;
            }

            in = new BufferedReader(new InputStreamReader(stream));
            StringBuilder responseBuilder = new StringBuilder();

            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                responseBuilder.append(inputLine);
            }

            body = responseBuilder.toString();
        } finally {
            if (in != null)
                in.close();
        }

        HTTPResponse response = new HTTPResponse();
        response.setResponseCode(responseCode, failed);
        response.setResponseBody(body);

        int i = 0;
        String headerName, headerContent;
        while ((headerName = connection.getHeaderFieldKey(i)) != null) {
            headerContent = connection.getHeaderField(i);
            response.addHeader(headerName, headerContent);
        }

        // ***  REDIRECTION  ***

        switch (responseCode) {
        case 301:
        case 302:
        case 307:
        case 308:
            if (response.getHeaders().containsKey("Location")) {
                response = makeRequest(response.getHeaders().get("Location"), method, data);
            }
        }

        // ***  END  ***

        return response;
    } finally {
        connection.disconnect();
    }
}

From source file:org.cruxframework.crux.core.server.rest.spi.HttpUtil.java

public static String wGet(String targetURL, String urlParameters, String method, String locale) {
    URL url;/* ww w  .j a  v a  2  s . c o m*/
    HttpURLConnection connection = null;
    try {
        //Create connection
        if (method != null && method.equals("GET") && !StringUtils.isEmpty(urlParameters)) {
            targetURL += "?" + urlParameters;
        }

        url = new URL(targetURL);
        connection = (HttpURLConnection) url.openConnection();

        connection.setRequestMethod(method);
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
        connection.setRequestProperty("Content-Language", locale);
        connection.setUseCaches(false);
        connection.setDoInput(true);

        //Send request
        if (method != null && method.equals("POST")) {
            DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
            connection.setDoOutput(true);
            wr.writeBytes(urlParameters);
            wr.flush();
            wr.close();
        }

        //Get Response   
        InputStream is = connection.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        StringBuffer response = new StringBuffer();
        while ((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\r');
        }
        rd.close();
        return response.toString();
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:org.wise.portal.presentation.web.filters.WISEAuthenticationProcessingFilter.java

/**
 * Check if the response is valid//from w  ww .j  a  va2 s  .c om
 * @param reCaptchaPrivateKey the ReCaptcha private key
 * @param reCaptchaPublicKey the ReCaptcha public key
 * @param gRecaptchaResponse the response
 * @return whether the user answered the ReCaptcha successfully
 */
public static boolean checkReCaptchaResponse(String reCaptchaPrivateKey, String reCaptchaPublicKey,
        String gRecaptchaResponse) {

    boolean isValid = false;

    //check if the public key is valid in case the admin entered it wrong
    boolean reCaptchaKeyValid = isReCaptchaKeyValid(reCaptchaPublicKey, reCaptchaPrivateKey);

    if (reCaptchaKeyValid && reCaptchaPrivateKey != null && reCaptchaPublicKey != null
            && gRecaptchaResponse != null && !gRecaptchaResponse.equals("")) {

        try {

            // the url to verify the response
            URL verifyURL = new URL("https://www.google.com/recaptcha/api/siteverify");
            HttpsURLConnection connection = (HttpsURLConnection) verifyURL.openConnection();
            connection.setRequestMethod("POST");

            // set the params
            String postParams = "secret=" + reCaptchaPrivateKey + "&response=" + gRecaptchaResponse;

            // make the request to verify if the user answered the ReCaptcha successfully
            connection.setDoOutput(true);
            DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
            outputStream.writeBytes(postParams);
            outputStream.flush();
            outputStream.close();

            BufferedReader bufferedReader = new BufferedReader(
                    new InputStreamReader(connection.getInputStream()));
            String inputLine = null;
            StringBuffer responseString = new StringBuffer();

            // read the response from the verify request
            while ((inputLine = bufferedReader.readLine()) != null) {
                responseString.append(inputLine);
            }

            bufferedReader.close();

            try {
                // create a JSON object from the response
                JSONObject responseObject = new JSONObject(responseString.toString());

                // get the value of the success field
                isValid = responseObject.getBoolean("success");
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return isValid;
}