Example usage for java.io DataOutputStream DataOutputStream

List of usage examples for java.io DataOutputStream DataOutputStream

Introduction

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

Prototype

public DataOutputStream(OutputStream out) 

Source Link

Document

Creates a new data output stream to write data to the specified underlying output stream.

Usage

From source file:com.db.comserv.main.utilities.HttpCaller.java

@Override
@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "DM_DEFAULT_ENCODING")
public HttpResult runRequest(String type, String methodType, URL url, List<Map<String, String>> headers,
        String requestBody, String sslByPassOption, int connTimeOut, int readTimeout, HttpServletRequest req)
        throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException,
        UnsupportedEncodingException, IOException, UnknownHostException, URISyntaxException {

    StringBuffer response = new StringBuffer();
    HttpResult httpResult = new HttpResult();
    boolean gzip = false;
    final long startNano = System.nanoTime();
    try {//from  www . j a v a 2s .co m
        URL encodedUrl = new URL(Utility.encodeUrl(url.toString()));
        HttpURLConnection con = (HttpURLConnection) encodedUrl.openConnection();
        TrustModifier.relaxHostChecking(con, sslByPassOption);

        // connection timeout 5s
        con.setConnectTimeout(connTimeOut);

        // read timeout 10s
        con.setReadTimeout(readTimeout * getQueryCost(req));

        methodType = methodType.toUpperCase();
        con.setRequestMethod(methodType);

        sLog.debug("Performing '{}' to '{}'", methodType, ServletUtil.filterUrl(url.toString()));

        // Get headers & set request property
        for (int i = 0; i < headers.size(); i++) {
            Map<String, String> header = headers.get(i);
            con.setRequestProperty(header.get("headerKey").toString(), header.get("headerValue").toString());
            sLog.debug("Setting Header '{}' with value '{}'", header.get("headerKey").toString(),
                    ServletUtil.filterHeaderValue(header.get("headerKey").toString(),
                            header.get("headerValue").toString()));
        }

        if (con.getRequestProperty("Accept-Encoding") == null) {
            con.setRequestProperty("Accept-Encoding", "gzip");
        }

        if (requestBody != null && !requestBody.equals("")) {
            con.setDoOutput(true);
            DataOutputStream wr = new DataOutputStream(con.getOutputStream());
            wr.write(Utility.toUtf8Bytes(requestBody));
            wr.flush();
            wr.close();

        }

        // push response
        BufferedReader in = null;
        String inputLine;

        List<String> contentEncoding = con.getHeaderFields().get("Content-Encoding");
        if (contentEncoding != null) {
            for (String val : contentEncoding) {
                if ("gzip".equalsIgnoreCase(val)) {
                    sLog.debug("Gzip enabled response");
                    gzip = true;
                    break;
                }
            }
        }

        sLog.debug("Response: '{} {}' with headers '{}'", con.getResponseCode(), con.getResponseMessage(),
                ServletUtil.buildHeadersForLog(con.getHeaderFields()));

        if (con.getResponseCode() != 200 && con.getResponseCode() != 201) {
            if (con.getErrorStream() != null) {
                if (gzip) {
                    in = new BufferedReader(
                            new InputStreamReader(new GZIPInputStream(con.getErrorStream()), "UTF-8"));
                } else {
                    in = new BufferedReader(new InputStreamReader(con.getErrorStream(), "UTF-8"));
                }
            }
        } else {
            String[] urlParts = url.toString().split("\\.");
            if (urlParts.length > 1) {
                String ext = urlParts[urlParts.length - 1];
                if (ext.equalsIgnoreCase("png") || ext.equalsIgnoreCase("jpg") || ext.equalsIgnoreCase("jpeg")
                        || ext.equalsIgnoreCase("gif")) {
                    BufferedImage imBuff;
                    if (gzip) {
                        imBuff = ImageIO.read(new GZIPInputStream(con.getInputStream()));
                    } else {
                        BufferedInputStream bfs = new BufferedInputStream(con.getInputStream());
                        imBuff = ImageIO.read(bfs);
                    }
                    BufferedImage newImage = new BufferedImage(imBuff.getWidth(), imBuff.getHeight(),
                            BufferedImage.TYPE_3BYTE_BGR);

                    // converting image to greyScale
                    int width = imBuff.getWidth();
                    int height = imBuff.getHeight();
                    for (int i = 0; i < height; i++) {
                        for (int j = 0; j < width; j++) {
                            Color c = new Color(imBuff.getRGB(j, i));
                            int red = (int) (c.getRed() * 0.21);
                            int green = (int) (c.getGreen() * 0.72);
                            int blue = (int) (c.getBlue() * 0.07);
                            int sum = red + green + blue;
                            Color newColor = new Color(sum, sum, sum);
                            newImage.setRGB(j, i, newColor.getRGB());
                        }
                    }

                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    ImageIO.write(newImage, "jpg", out);
                    byte[] bytes = out.toByteArray();

                    byte[] encodedBytes = Base64.encodeBase64(bytes);
                    String base64Src = new String(encodedBytes);
                    int imageSize = ((base64Src.length() * 3) / 4) / 1024;
                    int initialImageSize = imageSize;
                    int maxImageSize = Integer.parseInt(properties.getValue("Reduced_Image_Size"));
                    float quality = 0.9f;
                    if (!(imageSize <= maxImageSize)) {
                        //This means that image size is greater and needs to be reduced.
                        sLog.debug("Image size is greater than " + maxImageSize + " , compressing image.");
                        while (!(imageSize < maxImageSize)) {
                            base64Src = compress(base64Src, quality);
                            imageSize = ((base64Src.length() * 3) / 4) / 1024;
                            quality = quality - 0.1f;
                            DecimalFormat df = new DecimalFormat("#.0");
                            quality = Float.parseFloat(df.format(quality));
                            if (quality <= 0.1) {
                                break;
                            }
                        }
                    }
                    sLog.debug("Initial image size was : " + initialImageSize + " Final Image size is : "
                            + imageSize + "Url is : " + url + "quality is :" + quality);
                    String src = "data:image/" + urlParts[urlParts.length - 1] + ";base64,"
                            + new String(base64Src);
                    JSONObject joResult = new JSONObject();
                    joResult.put("Image", src);
                    out.close();
                    httpResult.setResponseCode(con.getResponseCode());
                    httpResult.setResponseHeader(con.getHeaderFields());
                    httpResult.setResponseBody(joResult.toString());
                    httpResult.setResponseMsg(con.getResponseMessage());
                    return httpResult;
                }
            }

            if (gzip) {
                in = new BufferedReader(
                        new InputStreamReader(new GZIPInputStream(con.getInputStream()), "UTF-8"));
            } else {
                in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
            }
        }
        if (in != null) {
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
        }

        httpResult.setResponseCode(con.getResponseCode());
        httpResult.setResponseHeader(con.getHeaderFields());
        httpResult.setResponseBody(response.toString());
        httpResult.setResponseMsg(con.getResponseMessage());

    } catch (Exception e) {
        sLog.error("Failed to received HTTP response after timeout", e);

        httpResult.setTimeout(true);
        httpResult.setResponseCode(500);
        httpResult.setResponseMsg("Internal Server Error Timeout");
        return httpResult;
    }

    return httpResult;
}

From source file:Main.java

@SuppressWarnings("resource")
public static String post(String targetUrl, Map<String, String> params, String file, byte[] data) {
    Logd(TAG, "Starting post...");
    String html = "";
    Boolean cont = true;//from  w w  w. j  a v a2  s  .c o  m
    URL url = null;
    try {
        url = new URL(targetUrl);
    } catch (MalformedURLException e) {
        Log.e(TAG, "Invalid url: " + targetUrl);
        cont = false;
        throw new IllegalArgumentException("Invalid url: " + targetUrl);
    }
    if (cont) {
        if (!targetUrl.startsWith("https") || gVALID_SSL.equals("true")) {
            HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.STRICT_HOSTNAME_VERIFIER;
            HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
        } else {
            // Create a trust manager that does not validate certificate chains
            TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
                @Override
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                    // TODO Auto-generated method stub
                }

                @Override
                public void checkServerTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                    // TODO Auto-generated method stub
                }
            } };
            // Install the all-trusting trust manager
            SSLContext sc;
            try {
                sc = SSLContext.getInstance("SSL");
                sc.init(null, trustAllCerts, new java.security.SecureRandom());
                HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
                // Create all-trusting host name verifier
                HostnameVerifier allHostsValid = new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        return true;
                    }
                };
                // Install the all-trusting host verifier
                HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
            } catch (NoSuchAlgorithmException e) {
                Logd(TAG, "Error: " + e.getLocalizedMessage());
            } catch (KeyManagementException e) {
                Logd(TAG, "Error: " + e.getLocalizedMessage());
            }
        }
        Logd(TAG, "Filename: " + file);
        Logd(TAG, "URL: " + targetUrl);
        HttpURLConnection connection = null;
        DataOutputStream outputStream = null;
        String pathToOurFile = file;
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024;
        try {
            connection = (HttpURLConnection) url.openConnection();
            // Allow Inputs & Outputs
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);
            //Don't use chunked post requests (nginx doesn't support requests without a Content-Length header)
            //connection.setChunkedStreamingMode(1024);
            // Enable POST method
            connection.setRequestMethod("POST");
            setBasicAuthentication(connection, url);
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
            outputStream = new DataOutputStream(connection.getOutputStream());
            //outputStream.writeBytes(twoHyphens + boundary + lineEnd);
            Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
            while (iterator.hasNext()) {
                Entry<String, String> param = iterator.next();
                outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                outputStream.writeBytes("Content-Disposition: form-data;" + "name=\"" + param.getKey() + "\""
                        + lineEnd + lineEnd);
                outputStream.write(param.getValue().getBytes("UTF-8"));
                outputStream.writeBytes(lineEnd);
            }
            String connstr = null;
            if (!file.equals("")) {
                FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile));
                outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                connstr = "Content-Disposition: form-data; name=\"upfile\";filename=\"" + pathToOurFile + "\""
                        + lineEnd;
                outputStream.writeBytes(connstr);
                outputStream.writeBytes(lineEnd);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                buffer = new byte[bufferSize];
                // Read file
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                Logd(TAG, "File length: " + bytesAvailable);
                try {
                    while (bytesRead > 0) {
                        try {
                            outputStream.write(buffer, 0, bufferSize);
                        } catch (OutOfMemoryError e) {
                            e.printStackTrace();
                            html = "Error: outofmemoryerror";
                            return html;
                        }
                        bytesAvailable = fileInputStream.available();
                        bufferSize = Math.min(bytesAvailable, maxBufferSize);
                        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                    }
                } catch (Exception e) {
                    Logd(TAG, "Error: " + e.getLocalizedMessage());
                    html = "Error: Unknown error";
                    return html;
                }
                outputStream.writeBytes(lineEnd);
                fileInputStream.close();
            } else if (data != null) {
                outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                connstr = "Content-Disposition: form-data; name=\"upfile\";filename=\"tmp\"" + lineEnd;
                outputStream.writeBytes(connstr);
                outputStream.writeBytes(lineEnd);
                bytesAvailable = data.length;
                Logd(TAG, "File length: " + bytesAvailable);
                try {
                    outputStream.write(data, 0, data.length);
                } catch (OutOfMemoryError e) {
                    e.printStackTrace();
                    html = "Error: outofmemoryerror";
                    return html;
                } catch (Exception e) {
                    Logd(TAG, "Error: " + e.getLocalizedMessage());
                    html = "Error: Unknown error";
                    return html;
                }
                outputStream.writeBytes(lineEnd);
            }
            outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
            // Responses from the server (code and message)
            int serverResponseCode = connection.getResponseCode();
            String serverResponseMessage = connection.getResponseMessage();
            Logd(TAG, "Server Response Code " + serverResponseCode);
            Logd(TAG, "Server Response Message: " + serverResponseMessage);
            if (serverResponseCode == 200) {
                InputStreamReader in = new InputStreamReader(connection.getInputStream());
                BufferedReader br = new BufferedReader(in);
                String decodedString;
                while ((decodedString = br.readLine()) != null) {
                    html += decodedString;
                }
                in.close();
            }
            outputStream.flush();
            outputStream.close();
            outputStream = null;
        } catch (Exception ex) {
            // Exception handling
            html = "Error: Unknown error";
            Logd(TAG, "Send file Exception: " + ex.getMessage());
        }
    }
    if (html.startsWith("success:"))
        Logd(TAG, "Server returned: success:HIDDEN");
    else
        Logd(TAG, "Server returned: " + html);
    return html;
}

From source file:es.logongas.util.seguridad.CodigoVerificacionSeguro.java

private static String createValor(int key) {
    try {//www  . j  av a2  s . c  om
        //Generar el N aleatorio
        int numeroAleatorio = new Random().nextInt(Integer.MAX_VALUE);
        CRC crc = new CRC();
        crc.update(key).update(numeroAleatorio);

        //Genera el array de datos con el tipo, key y el n aleatorio
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        DataOutputStream dataOutputStream = new DataOutputStream(byteArrayOutputStream);
        dataOutputStream.writeInt(key);
        dataOutputStream.writeInt(numeroAleatorio);
        dataOutputStream.writeInt(crc.getCRC());

        byte[] datos = byteArrayOutputStream.toByteArray();

        //Trasformarlo en un String en Base32
        Base32 base32 = new Base32();
        String codigoVerificacionSeguro = base32.encodeAsString(datos);

        //Quitamos el "=" del final pq no se puedo codificar con el cdigo de barras.
        codigoVerificacionSeguro = codigoVerificacionSeguro.substring(0, codigoVerificacionSeguro.indexOf('='));

        return codigoVerificacionSeguro;
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }

}

From source file:iics.Connection.java

public String excutePost(String targetURL, String urlParameters) {

    URL url;// w  ww  .ja v  a 2s  .  c o  m
    HttpURLConnection connection = null;
    try {
        //Create connection
        url = new URL(targetURL);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        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);

        //Send request
        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        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) {
            if (!line.equals("")) {
                response.append(line);
            }
            //response.append('\r');
        }
        rd.close();

        // System.out.println("gigig " + response.toString());
        if (response.toString().substring(0, 8).equals("Response")) {
            String[] dett = response.toString().split("~~~");
            det = dett[1];
            create_dir();
            openweb(f.toString());
        } else {
            //System.out.println("err "+ex.getMessage());
            JOptionPane.showMessageDialog(null,
                    "                 An error occured!! \n Try again later or contact your system admin for help.");
            close_loda();
        }
        return response.toString();

    } catch (Exception e) {

        JOptionPane.showMessageDialog(null,
                "                 An error occured!! \n Contact your system admin for help.", null,
                JOptionPane.WARNING_MESSAGE);
        close_loda();
        return null;

    } finally {

        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:gridool.util.xfer.RecievedFileWriter.java

public final void handleRequest(@Nonnull final SocketChannel inChannel, @Nonnull final Socket socket)
        throws IOException {
    final StopWatch sw = new StopWatch();
    if (!inChannel.isBlocking()) {
        inChannel.configureBlocking(true);
    }/* www .ja  va  2 s.co  m*/

    InputStream in = socket.getInputStream();
    DataInputStream dis = new DataInputStream(in);

    String fname = IOUtils.readString(dis);
    String dirPath = IOUtils.readString(dis);
    long len = dis.readLong();
    boolean append = dis.readBoolean();
    boolean ackRequired = dis.readBoolean();
    boolean hasAdditionalHeader = dis.readBoolean();
    if (hasAdditionalHeader) {
        readAdditionalHeader(dis, fname, dirPath, len, append, ackRequired);
    }

    final File file;
    if (dirPath == null) {
        file = new File(baseDir, fname);
    } else {
        File dir = FileUtils.resolvePath(baseDir, dirPath);
        file = new File(dir, fname);
    }

    preFileAppend(file, append);
    final FileOutputStream dst = new FileOutputStream(file, append);
    final String fp = file.getAbsolutePath();
    final ReadWriteLock filelock = accquireLock(fp, locks);
    final FileChannel fileCh = dst.getChannel();
    final long startPos = file.length();
    try {
        NIOUtils.transferFully(inChannel, 0, len, fileCh); // REVIEWME really an atomic operation?
    } finally {
        IOUtils.closeQuietly(fileCh, dst);
        releaseLock(fp, filelock, locks);
        postFileAppend(file, startPos, len);
    }
    if (ackRequired) {
        OutputStream out = socket.getOutputStream();
        DataOutputStream dos = new DataOutputStream(out);
        dos.writeLong(len);
        postAck(file, startPos, len);
    }

    if (LOG.isDebugEnabled()) {
        SocketAddress remoteAddr = socket.getRemoteSocketAddress();
        LOG.debug("Received a " + (append ? "part of file '" : "file '") + file.getAbsolutePath() + "' of "
                + len + " bytes from " + remoteAddr + " in " + sw.toString());
    }
}

From source file:admincommands.Unishell.java

@Override
public void executeCommand(Player admin, String[] params) {
    if (admin.getAccessLevel() < 3) {
        PacketSendUtility.sendMessage(admin, "You dont have enough rights to execute this command");
        return;//from   ww w . j  av a  2 s.  c  o m
    }

    if (params.length < 2) {
        PacketSendUtility.sendMessage(admin, "Syntax: //unishell <useradd|show> <values...>");
        PacketSendUtility.sendMessage(admin, "//unishell useradd username password");
        PacketSendUtility.sendMessage(admin, "//unishell show users");
        return;
    }

    if (params[0].equals("adduser")) {
        if (params.length < 3) {
            PacketSendUtility.sendMessage(admin, "Syntax; //unishell useradd username password");
            return;
        }

        String username = params[1];
        String password = params[2];
        String hashedPassword = CryptoHelper.encodeSHA1(password);

        Map<String, String> actualAuthorizedKeys = AuthorizedKeys.loadAuthorizedKeys();
        Iterator<Entry<String, String>> actualAuthorizedEntries = actualAuthorizedKeys.entrySet().iterator();
        boolean checkResult = false;
        while (actualAuthorizedEntries.hasNext()) {
            if (username.equals(actualAuthorizedEntries.next().getKey())) {
                checkResult = true;
            }
        }

        if (checkResult) {
            PacketSendUtility.sendMessage(admin, "Error: username already exists.");
            return;
        }

        try {
            FileOutputStream file = new FileOutputStream("./config/network/unishell.passwd", true);
            DataOutputStream out = new DataOutputStream(file);
            out.writeBytes(username + ":" + hashedPassword + "\n");
            out.flush();
            out.close();
            PacketSendUtility.sendMessage(admin, "Unishell user '" + username + "' successfully added !");
            return;
        } catch (FileNotFoundException fnfe) {
            log.error("Cannot open unishell password file for writing at ./config/network/unishell.passwd",
                    fnfe);
            PacketSendUtility.sendMessage(admin, "Error: cannot open password file.");
            return;
        } catch (IOException ioe) {
            log.error("Cannot write to unishell password file for writing at ./config/network/unishell.passwd",
                    ioe);
            PacketSendUtility.sendMessage(admin, "Error: cannot write to password file.");
            return;
        }

    } else if (params[0].equals("show")) {
        if (params.length < 2) {
            PacketSendUtility.sendMessage(admin, "Syntax: //unishell show users");
            return;
        }

        if (params[1].equals("users")) {
            Iterator<Entry<String, String>> authorizedKeys = AuthorizedKeys.loadAuthorizedKeys().entrySet()
                    .iterator();
            while (authorizedKeys.hasNext()) {
                Entry<String, String> current = authorizedKeys.next();
                PacketSendUtility.sendMessage(admin,
                        "user: " + current.getKey() + " | password: " + current.getValue());
            }
        }

    } else {
        PacketSendUtility.sendMessage(admin, "Syntax: //unishell <useradd|> <values...>");
        PacketSendUtility.sendMessage(admin, "//unishell useradd username password");
        return;
    }

}

From source file:de.cubeisland.engine.core.util.McUUID.java

private static HttpURLConnection postQuery(ArrayNode node, int page) throws IOException {
    HttpURLConnection con = (HttpURLConnection) new URL(MOJANG_API_URL_NAME_UUID + page).openConnection();
    con.setRequestMethod("POST");
    con.setRequestProperty("Content-Type", "application/json");
    con.setUseCaches(false);/*from  w w w  . j  a va 2s  .  co  m*/
    con.setDoInput(true);
    con.setDoOutput(true);
    DataOutputStream writer = new DataOutputStream(con.getOutputStream());
    writer.write(node.toString().getBytes());
    writer.close();
    return con;
}

From source file:edu.mda.bioinfo.ids.DownloadFiles.java

private void downloadFromHttpToFile(String theURL, String theParameters, String theFile) throws IOException {
    // both in milliseconds
    //int connectionTimeout = 1000 * 60 * 3;
    //int readTimeout = 1000 * 60 * 3;
    try {//from   ww w  . ja v  a2  s  .c o m
        URL myURL = new URL(theURL);
        HttpURLConnection connection = (HttpURLConnection) myURL.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setInstanceFollowRedirects(false);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "text/plain");
        //connection.setRequestProperty("charset", "utf-8");
        if (null != theParameters) {
            System.out.println("Content-Length " + Integer.toString(theParameters.getBytes().length));
            connection.setRequestProperty("Content-Length",
                    "" + Integer.toString(theParameters.getBytes().length));
        }
        connection.setUseCaches(false);
        try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
            if (null != theParameters) {
                wr.write(theParameters.getBytes());
            }
            wr.flush();
            File myFile = new File(theFile);
            System.out.println("Requesting " + myURL);
            FileUtils.copyInputStreamToFile(connection.getInputStream(), myFile);
            System.out.println("Downloaded " + myURL);
        } catch (IOException rethrownExp) {
            InputStream errorStr = connection.getErrorStream();
            if (null != errorStr) {
                System.err.println("Error stream returned: " + IOUtils.toString(errorStr));
            } else {
                System.err.println("No error stream returned");
            }
            throw rethrownExp;
        }
    } catch (IOException rethrownExp) {
        System.err.println("exception " + rethrownExp.getMessage() + " thrown while downloading " + theURL
                + " to " + theFile);
        throw rethrownExp;
    }
}

From source file:com.amazon.alexa.avs.companion.ProvisioningClient.java

JSONObject doRequest(HttpURLConnection connection, String data) throws IOException, JSONException {
    int responseCode = -1;
    InputStream response = null;/*w w w.  jav a  2  s . com*/
    DataOutputStream outputStream = null;

    try {
        if (connection instanceof HttpsURLConnection) {
            ((HttpsURLConnection) connection).setSSLSocketFactory(pinnedSSLSocketFactory);
        }

        connection.setRequestProperty("Content-Type", "application/json");
        if (data != null) {
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);

            outputStream = new DataOutputStream(connection.getOutputStream());
            outputStream.write(data.getBytes());
            outputStream.flush();
            outputStream.close();
        } else {
            connection.setRequestMethod("GET");
        }

        responseCode = connection.getResponseCode();
        response = connection.getInputStream();

        if (responseCode != 204) {
            String responseString = IOUtils.toString(response);
            JSONObject jsonObject = new JSONObject(responseString);
            return jsonObject;
        } else {
            return null;
        }
    } catch (IOException e) {
        if (responseCode < 200 || responseCode >= 300) {
            response = connection.getErrorStream();
            if (response != null) {
                String responseString = IOUtils.toString(response);
                throw new RuntimeException(responseString);
            }
        }
        throw e;
    } finally {
        IOUtils.closeQuietly(outputStream);
        IOUtils.closeQuietly(response);
    }
}

From source file:com.letsgood.synergykitsdkandroid.requestmethods.Post.java

@Override
public BufferedReader execute() {
    String jSon = null;//from  w w  w.j  av a2 s .  c  om
    String uri = null;

    //init check
    if (!Synergykit.isInit()) {
        SynergykitLog.print(Errors.MSG_SK_NOT_INITIALIZED);

        statusCode = Errors.SC_SK_NOT_INITIALIZED;
        return null;
    }

    //URI check
    uri = getUri().toString();

    if (uri == null) {
        statusCode = Errors.SC_URI_NOT_VALID;
        return null;
    }

    //session token check
    if (sessionTokenRequired && sessionToken == null) {
        statusCode = Errors.SC_NO_SESSION_TOKEN;
        return null;
    }

    try {
        url = new URL(uri); // init url

        httpURLConnection = (HttpURLConnection) url.openConnection(); //open connection
        httpURLConnection.setConnectTimeout(CONNECT_TIMEOUT); //set connect timeout
        httpURLConnection.setReadTimeout(READ_TIMEOUT); //set read timeout
        httpURLConnection.setRequestMethod(REQUEST_METHOD); //set method
        httpURLConnection.addRequestProperty(PROPERTY_USER_AGENT, PROPERTY_USER_AGENT_VALUE); //set property accept
        httpURLConnection.addRequestProperty(PROPERTY_ACCEPT, ACCEPT_APPLICATION_VALUE); //set property accept
        httpURLConnection.addRequestProperty(PROPERTY_CONTENT_TYPE, ACCEPT_APPLICATION_VALUE);
        httpURLConnection.setDoInput(true);
        httpURLConnection.setDoOutput(true);

        httpURLConnection.addRequestProperty(PROPERTY_AUTHORIZATION,
                "Basic " + Base64.encodeToString(
                        (Synergykit.getTenant() + ":" + Synergykit.getApplicationKey()).getBytes(),
                        Base64.NO_WRAP)); //set authorization

        if (Synergykit.getSessionToken() != null)
            httpURLConnection.addRequestProperty(PROPERTY_SESSION_TOKEN, Synergykit.getSessionToken());

        httpURLConnection.connect();

        //write data
        if (object != null) {
            jSon = GsonWrapper.getGson().toJson(object);
            dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());
            dataOutputStream.write(jSon.getBytes(CHARSET));
            dataOutputStream.flush();
            dataOutputStream.close();
        }

        statusCode = httpURLConnection.getResponseCode(); //get status code

        //read stream
        if (statusCode >= HttpURLConnection.HTTP_OK && statusCode < HttpURLConnection.HTTP_MULT_CHOICE) {
            return readStream(httpURLConnection.getInputStream());
        } else {
            return readStream(httpURLConnection.getErrorStream());
        }

    } catch (Exception e) {
        statusCode = HttpStatus.SC_SERVICE_UNAVAILABLE;
        e.printStackTrace();
        return null;
    }

}