Example usage for java.io DataOutputStream close

List of usage examples for java.io DataOutputStream close

Introduction

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

Prototype

@Override
public void close() throws IOException 

Source Link

Document

Closes this output stream and releases any system resources associated with the stream.

Usage

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

public static int post(String url, JSONObject json, String username, String password) throws IOException {
    HttpURLConnection conn = createConnection(url, username, password);

    conn.setRequestMethod("POST");
    conn.setRequestProperty("Connection", "Keep-Alive");
    conn.setRequestProperty("Content-Type", "application/json");

    byte[] jsonBytes = json.toString().getBytes("UTF-8");

    conn.setRequestProperty("Content-Length", Integer.toString(jsonBytes.length));

    DataOutputStream out = new DataOutputStream(conn.getOutputStream());
    out.write(jsonBytes);/* w w w.  ja va 2 s  .co  m*/
    out.flush();

    InputStream in = conn.getInputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(in), 2048);

    for (String line = reader.readLine(); line != null; line = reader.readLine()) {
    }
    out.close();

    int responseCode = 0;
    responseCode = conn.getResponseCode();
    return responseCode;
}

From source file:eu.crowdrec.contest.sender.RequestSender.java

/**
 * Send a line from a logFile to an HTTP server (single-threaded).
 * /*from w ww  .ja  v  a2 s .  c om*/
 * @param logline the line that should by sent
 * 
 * @param connection the connection to the http server, must not be null
 * 
 * @return the response or null (if an error has been detected)
 */
static private String excutePost(final String logline, final String serverURL) {

    // split the logLine into several token
    String[] token = logline.split("\t");

    String type = token[0];
    String property = token[3];
    String entity = token[4];

    // encode the content as URL parameters.
    String urlParameters = "";
    try {
        urlParameters = String.format("type=%s&properties=%s&entities=%s", URLEncoder.encode(type, "UTF-8"),
                URLEncoder.encode(property, "UTF-8"), URLEncoder.encode(entity, "UTF-8"));
    } catch (UnsupportedEncodingException e1) {
        logger.warn(e1.toString());
    }

    // initialize a HTTP connection to the server
    // reuse of connection objects is delegated to the JVM
    HttpURLConnection connection = null;

    try {
        final URL url = new URL(serverURL);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("Content-Language", "en-US");
        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));

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

        // Get Response
        BufferedReader rd = null;
        InputStream is = null;
        try {
            is = connection.getInputStream();
            rd = new BufferedReader(new InputStreamReader(is));

            StringBuffer response = new StringBuffer();
            for (String line = rd.readLine(); line != null; line = rd.readLine()) {
                response.append(line);
                response.append(" ");
            }
            return response.toString();
        } catch (IOException e) {
            logger.warn("receivind response failed, ignored.");
        } finally {
            if (is != null) {
                is.close();
            }
            if (rd != null) {
                rd.close();
            }
        }
    } catch (MalformedURLException e) {
        System.err.println("invalid server URL, program stopped.");
        System.exit(-1);
    } catch (IOException e) {
        System.err.println("i/o error connecting the http server, program stopped. e=" + e);
        System.exit(-1);
    } catch (Exception e) {
        System.err.println("general error connecting the http server, program stopped. e:" + e);
        e.printStackTrace();
        System.exit(-1);
    } finally {
        // close the connection
        if (connection != null) {
            connection.disconnect();
        }
    }
    return null;
}

From source file:BihuHttpUtil.java

/**
 * ??HTTPJSON?//from w w w. j  av  a  2 s.  co  m
 * @param url
 * @param jsonStr
 */
public static String sendPostForJson(String url, String jsonStr) {
    StringBuffer sb = new StringBuffer("");
    try {
        //
        URL realUrl = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestMethod("POST");
        connection.setUseCaches(false);
        connection.setInstanceFollowRedirects(true);
        connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        connection.connect();
        //POST
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        out.write(jsonStr.getBytes("UTF-8"));//???
        out.flush();
        out.close();
        //??
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String lines;
        while ((lines = reader.readLine()) != null) {
            lines = new String(lines.getBytes(), "utf-8");
            sb.append(lines);
        }
        reader.close();
        // 
        connection.disconnect();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return sb.toString();
}

From source file:com.mopaas_mobile.http.BaseHttpRequester.java

public static String doPOST(String urlstr, List<BasicNameValuePair> params) throws IOException {
    String result = null;/*from w w w  . j  a v  a 2  s.c  o m*/
    URL url = new URL(urlstr);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setRequestMethod("POST");
    connection.setUseCaches(false);
    connection.setInstanceFollowRedirects(false);
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    //       connection.setRequestProperty("token",token);
    connection.setConnectTimeout(30000);
    connection.setReadTimeout(30000);
    connection.connect();

    DataOutputStream out = new DataOutputStream(connection.getOutputStream());

    String content = "";
    if (params != null && params.size() > 0) {
        for (int i = 0; i < params.size(); i++) {
            content = content + "&" + URLEncoder.encode(((NameValuePair) params.get(i)).getName(), "UTF-8")
                    + "=" + URLEncoder.encode(((NameValuePair) params.get(i)).getValue(), "UTF-8");
        }
        out.writeBytes(content.substring(1));
    }

    out.flush();
    out.close();
    InputStream is = connection.getInputStream();
    BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

    StringBuffer b = new StringBuffer();
    int ch;
    while ((ch = br.read()) != -1) {
        b.append((char) ch);
    }
    result = b.toString().trim();
    connection.disconnect();
    return result;
}

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 .  ja v  a2  s  .c o  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:com.alibaba.rocketmq.tools.command.message.QueryMsgByIdSubCommand.java

private static String createBodyFile(MessageExt msg) throws IOException {
    DataOutputStream dos = null;

    try {/*from  w  w  w. j av a2  s. com*/
        String bodyTmpFilePath = "/tmp/rocketmq/msgbodys";
        File file = new File(bodyTmpFilePath);
        if (!file.exists()) {
            file.mkdirs();
        }
        bodyTmpFilePath = bodyTmpFilePath + "/" + msg.getMsgId();
        dos = new DataOutputStream(new FileOutputStream(bodyTmpFilePath));
        dos.write(msg.getBody());
        return bodyTmpFilePath;
    } finally {
        if (dos != null)
            dos.close();
    }
}

From source file:com.ict.dtube.tools.command.message.QueryMsgByIdSubCommand.java

private static String createBodyFile(MessageExt msg) throws IOException {
    DataOutputStream dos = null;

    try {/*from ww w  .j a va2  s.c o  m*/
        String bodyTmpFilePath = "/tmp/dtube/msgbodys";
        File file = new File(bodyTmpFilePath);
        if (!file.exists()) {
            file.mkdirs();
        }
        bodyTmpFilePath = bodyTmpFilePath + "/" + msg.getMsgId();
        dos = new DataOutputStream(new FileOutputStream(bodyTmpFilePath));
        dos.write(msg.getBody());
        return bodyTmpFilePath;
    } finally {
        if (dos != null)
            dos.close();
    }
}

From source file:disko.DU.java

public static String request(String targetUrl, String method, String text, String contentType)
        throws Exception {
    URL url = new URL(targetUrl);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    if (method != null)
        conn.setRequestMethod(method);/*from w w w. jav a  2s.  c om*/

    if (contentType != null)
        conn.setRequestProperty("Content-Type", contentType);

    if (text != null) {
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.getOutputStream().write(text.getBytes());
        DataOutputStream out = new DataOutputStream(conn.getOutputStream());
        out.write(text.getBytes());
        out.flush();
        out.close();
    }

    if (conn.getResponseCode() != 200)
        throw new RuntimeException("HTTPClient failed: " + conn.getResponseCode());

    StringBuffer responseBuffer = new StringBuffer();
    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line;
    String eol = new String(new byte[] { 13 });
    while ((line = in.readLine()) != null) {
        responseBuffer.append(line);
        responseBuffer.append(eol);
    }
    in.close();

    return responseBuffer.toString();
}

From source file:com.chiorichan.util.WebUtils.java

public static boolean sendTracking(String category, String action, String label) {
    String url = "http://www.google-analytics.com/collect";
    try {/*from ww  w  .  j  ava 2 s  .c om*/
        URL urlObj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
        con.setRequestMethod("POST");

        String urlParameters = "v=1&tid=UA-60405654-1&cid=" + Loader.getClientId() + "&t=event&ec=" + category
                + "&ea=" + action + "&el=" + label;

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

        int responseCode = con.getResponseCode();
        Loader.getLogger().fine("Analytics Response [" + category + "]: " + 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();

        return true;
    } catch (IOException e) {
        return false;
    }
}

From source file:org.eclipse.swt.snippets.Snippet319.java

static byte[] convertToByteArray(MyType type) {
    DataOutputStream dataOutStream = null;
    try {// w w  w. j a v a 2  s . c  o m
        ByteArrayOutputStream byteOutStream = new ByteArrayOutputStream();
        dataOutStream = new DataOutputStream(byteOutStream);
        byte[] bytes = type.name.getBytes();
        dataOutStream.writeInt(bytes.length);
        dataOutStream.write(bytes);
        dataOutStream.writeLong(type.time);
        return byteOutStream.toByteArray();
    } catch (IOException e) {
        return null;
    } finally {
        if (dataOutStream != null) {
            try {
                dataOutStream.close();
            } catch (IOException e) {
            }
        }
    }
}