List of usage examples for java.io DataOutputStream close
@Override public void close() throws IOException
From source file:gov.nasa.arc.geocam.geocam.HttpPost.java
public static int post(String url, Map<String, String> vars, String fileKey, String fileName, InputStream istream, String username, String password) throws IOException { HttpURLConnection conn = createConnection(url, username, password); try {//from w ww . ja v a2 s . c o m conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); Log.d("HttpPost", vars.toString()); DataOutputStream out = new DataOutputStream(conn.getOutputStream()); assembleMultipart(out, vars, fileKey, fileName, istream); istream.close(); out.flush(); InputStream in = conn.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in), 2048); // Set postedSuccess to true if there is a line in the HTTP response in // the form "GEOCAM_SHARE_POSTED <file>" where <file> equals fileName. // Our old success condition was just checking for HTTP return code 200; turns // out that sometimes gives false positives. Boolean postedSuccess = false; for (String line = reader.readLine(); line != null; line = reader.readLine()) { //Log.d("HttpPost", line); if (!postedSuccess && line.contains("GEOCAM_SHARE_POSTED")) { String[] vals = line.trim().split("\\s+"); for (int i = 0; i < vals.length; ++i) { //String filePosted = vals[1]; if (vals[i].equals(fileName)) { Log.d(GeoCamMobile.DEBUG_ID, line); postedSuccess = true; break; } } } } out.close(); int responseCode = 0; responseCode = conn.getResponseCode(); if (responseCode == 200 && !postedSuccess) { // our code for when we got value 200 but no confirmation responseCode = -3; } return responseCode; } catch (UnsupportedEncodingException e) { throw new IOException("HttpPost - Encoding exception: " + e); } // ??? when would this ever be thrown? catch (IllegalStateException e) { throw new IOException("HttpPost - IllegalState: " + e); } catch (IOException e) { try { return conn.getResponseCode(); } catch (IOException f) { throw new IOException("HttpPost - IOException: " + e); } } }
From source file:org.maikelwever.droidpile.backend.ApiConnecter.java
public String postData(ArrayList<NameValuePair> payload, String... data) throws IOException { if (data.length < 1) { throw new IllegalArgumentException("More than 1 argument is required."); }// w w w .ja v a2 s .com String url = this.baseUrl; String suffix = ""; for (String arg : data) { suffix += "/" + arg; } suffix += "/"; Log.d("droidpile", "URL we will call: " + url + suffix); url += suffix; URL uri = new URL(url); InputStreamReader is; HttpURLConnection con; if (url.startsWith("https")) { con = (HttpsURLConnection) uri.openConnection(); } else { con = (HttpURLConnection) uri.openConnection(); } String urlParameters = URLEncodedUtils.format(payload, ENCODING); con.setDoInput(true); con.setDoOutput(true); con.setInstanceFollowRedirects(false); con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); con.setRequestProperty("charset", ENCODING); con.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes(ENCODING).length)); con.setUseCaches(false); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); is = new InputStreamReader(con.getInputStream(), ENCODING); StringBuilder sb = new StringBuilder(); BufferedReader br = new BufferedReader(is); String read = br.readLine(); while (read != null) { sb.append(read); read = br.readLine(); } String stringData = sb.toString(); con.disconnect(); return stringData; }
From source file:io.dacopancm.socketdcm.net.StreamSocket.java
public String getStreamFile() { String list = "false"; try {/*from w ww .j av a2 s. c o m*/ if (ConectType.GET_STREAM.name().equalsIgnoreCase(method)) { logger.log(Level.INFO, "get stream socket call"); sock = new Socket(ip, port); DataOutputStream dOut = new DataOutputStream(sock.getOutputStream()); DataInputStream dIn = new DataInputStream(sock.getInputStream()); dOut.writeUTF(ConectType.STREAM.name());//send stream type dOut.writeUTF("uncompressed");//send comprimido o no dOut.writeUTF(ConectType.GET_STREAM.toString()); //send type dOut.writeUTF(streamid); dOut.flush(); // Send off the data String rtspId = dIn.readUTF(); dOut.close(); logger.log(Level.INFO, "resp get stream file: {0}", rtspId); list = rtspId; } } catch (IOException ex) { HelperUtil.showErrorB("No se pudo establecer conexin"); logger.log(Level.INFO, "get stream file error no connect:{0}", ex.getMessage()); try { if (sock != null) { sock.close(); } } catch (IOException e) { } } return list; }
From source file:J2MESearchMixedRecordDataTypeExample.java
public void commandAction(Command command, Displayable displayable) { if (command == exit) { destroyApp(true);// www. ja v a 2 s. c o m notifyDestroyed(); } else if (command == start) { try { recordstore = RecordStore.openRecordStore("myRecordStore", true); byte[] outputRecord; String outputString[] = { "A", "B", "M" }; int outputInteger[] = { 15, 10, 5 }; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); DataOutputStream outputDataStream = new DataOutputStream(outputStream); for (int x = 0; x < 3; x++) { outputDataStream.writeUTF(outputString[x]); outputDataStream.writeInt(outputInteger[x]); outputDataStream.flush(); outputRecord = outputStream.toByteArray(); recordstore.addRecord(outputRecord, 0, outputRecord.length); outputStream.reset(); } outputStream.close(); outputDataStream.close(); String inputString; byte[] byteInputData = new byte[300]; ByteArrayInputStream inputStream = new ByteArrayInputStream(byteInputData); DataInputStream inputDataStream = new DataInputStream(inputStream); if (recordstore.getNumRecords() > 0) { filter = new Filter("Mary"); recordEnumeration = recordstore.enumerateRecords(filter, null, false); while (recordEnumeration.hasNextElement()) { recordstore.getRecord(recordEnumeration.nextRecordId(), byteInputData, 0); inputString = inputDataStream.readUTF() + " " + inputDataStream.readInt(); alert = new Alert("Reading", inputString, null, AlertType.WARNING); alert.setTimeout(Alert.FOREVER); display.setCurrent(alert); } } inputStream.close(); recordstore.closeRecordStore(); if (RecordStore.listRecordStores() != null) { RecordStore.deleteRecordStore("myRecordStore"); filter.filterClose(); recordEnumeration.destroy(); } } catch (Exception error) { alert = new Alert("Error Removing", error.toString(), null, AlertType.WARNING); alert.setTimeout(Alert.FOREVER); display.setCurrent(alert); } } }
From source file:net.phalapi.sdk.PhalApiClient.java
protected String doRequest(String requestUrl, Map<String, String> params, int timeoutMs) throws Exception { String result = null;/*from ww w .jav a 2 s. c o m*/ URL url = null; HttpURLConnection connection = null; InputStreamReader in = null; url = new URL(requestUrl); connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestMethod("POST"); // ? connection.setUseCaches(false); connection.setConnectTimeout(timeoutMs); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); //POST? String postContent = ""; Iterator<Entry<String, String>> iter = params.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<String, String> entry = (Map.Entry<String, String>) iter.next(); postContent += "&" + entry.getKey() + "=" + entry.getValue(); } out.writeBytes(postContent); out.flush(); out.close(); Log.d("[PhalApiClient requestUrl]", requestUrl + postContent); in = new InputStreamReader(connection.getInputStream()); BufferedReader bufferedReader = new BufferedReader(in); StringBuffer strBuffer = new StringBuffer(); String line = null; while ((line = bufferedReader.readLine()) != null) { strBuffer.append(line); } result = strBuffer.toString(); Log.d("[PhalApiClient apiResult]", result); if (connection != null) { connection.disconnect(); } if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } return result; }
From source file:J2MESortMixedRecordDataTypeExample.java
public void commandAction(Command command, Displayable displayable) { if (command == exit) { destroyApp(true);//from w ww . ja v a 2 s. co m notifyDestroyed(); } else if (command == start) { try { recordstore = RecordStore.openRecordStore("myRecordStore", true); byte[] outputRecord; String outputString[] = { "Mary", "Bob", "Adam" }; int outputInteger[] = { 15, 10, 5 }; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); DataOutputStream outputDataStream = new DataOutputStream(outputStream); for (int x = 0; x < 3; x++) { outputDataStream.writeUTF(outputString[x]); outputDataStream.writeInt(outputInteger[x]); outputDataStream.flush(); outputRecord = outputStream.toByteArray(); recordstore.addRecord(outputRecord, 0, outputRecord.length); outputStream.reset(); } outputStream.close(); outputDataStream.close(); String[] inputString = new String[3]; byte[] byteInputData = new byte[300]; ByteArrayInputStream inputStream = new ByteArrayInputStream(byteInputData); DataInputStream inputDataStream = new DataInputStream(inputStream); StringBuffer buffer = new StringBuffer(); comparator = new Comparator(); recordEnumeration = recordstore.enumerateRecords(null, comparator, false); while (recordEnumeration.hasNextElement()) { recordstore.getRecord(recordEnumeration.nextRecordId(), byteInputData, 0); buffer.append(inputDataStream.readUTF()); buffer.append(inputDataStream.readInt()); buffer.append("\n"); inputDataStream.reset(); } alert = new Alert("Reading", buffer.toString(), null, AlertType.WARNING); alert.setTimeout(Alert.FOREVER); display.setCurrent(alert); inputDataStream.close(); inputStream.close(); recordstore.closeRecordStore(); if (RecordStore.listRecordStores() != null) { RecordStore.deleteRecordStore("myRecordStore"); comparator.compareClose(); recordEnumeration.destroy(); } } catch (Exception error) { alert = new Alert("Error Removing", error.toString(), null, AlertType.WARNING); alert.setTimeout(Alert.FOREVER); display.setCurrent(alert); } } }
From source file:me.rojo8399.placeholderapi.impl.Metrics.java
/** * Sends the data to the bStats server.// w w w . j a v a 2 s. c o m * * @param data * The data to send. * @throws Exception * If the request failed. */ private static void sendData(JsonObject data) throws Exception { Validate.notNull(data, "Data cannot be null"); HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection(); // Compress the data to save bandwidth byte[] compressedData = compress(data.toString()); // Add headers connection.setRequestMethod("POST"); connection.addRequestProperty("Accept", "application/json"); connection.addRequestProperty("Connection", "close"); connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip // our // request connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); connection.setRequestProperty("Content-Type", "application/json"); // We // send // our // data // in // JSON // format connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION); // Send data connection.setDoOutput(true); DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream()); outputStream.write(compressedData); outputStream.flush(); outputStream.close(); connection.getInputStream().close(); // We don't care about the response // - Just send our data :) }
From source file:org.alfresco.mobile.android.api.network.NetworkHttpInvoker.java
private static Response invoke(UrlBuilder url, String method, String contentType, Map<String, List<String>> httpHeaders, Output writer, boolean forceOutput, BigInteger offset, BigInteger length, Map<String, String> params) { try {//from w w w.ja va 2 s .c o m // Log.d("URL", url.toString()); // connect HttpURLConnection conn = (HttpURLConnection) (new URL(url.toString())).openConnection(); conn.setRequestMethod(method); conn.setDoInput(true); conn.setDoOutput(writer != null || forceOutput); conn.setAllowUserInteraction(false); conn.setUseCaches(false); conn.setRequestProperty("User-Agent", ClientVersion.OPENCMIS_CLIENT); // set content type if (contentType != null) { conn.setRequestProperty("Content-Type", contentType); } // set other headers if (httpHeaders != null) { for (Map.Entry<String, List<String>> header : httpHeaders.entrySet()) { if (header.getValue() != null) { for (String value : header.getValue()) { conn.addRequestProperty(header.getKey(), value); } } } } // range BigInteger tmpOffset = offset; if ((tmpOffset != null) || (length != null)) { StringBuilder sb = new StringBuilder("bytes="); if ((tmpOffset == null) || (tmpOffset.signum() == -1)) { tmpOffset = BigInteger.ZERO; } sb.append(tmpOffset.toString()); sb.append("-"); if ((length != null) && (length.signum() == 1)) { sb.append(tmpOffset.add(length.subtract(BigInteger.ONE)).toString()); } conn.setRequestProperty("Range", sb.toString()); } conn.setRequestProperty("Accept-Encoding", "gzip,deflate"); // add url form parameters if (params != null) { DataOutputStream ostream = null; OutputStream os = null; try { os = conn.getOutputStream(); ostream = new DataOutputStream(os); Set<String> parameters = params.keySet(); StringBuffer buf = new StringBuffer(); int paramCount = 0; for (String it : parameters) { String parameterName = it; String parameterValue = (String) params.get(parameterName); if (parameterValue != null) { parameterValue = URLEncoder.encode(parameterValue, "UTF-8"); if (paramCount > 0) { buf.append("&"); } buf.append(parameterName); buf.append("="); buf.append(parameterValue); ++paramCount; } } ostream.writeBytes(buf.toString()); } finally { if (ostream != null) { ostream.flush(); ostream.close(); } IOUtils.closeStream(os); } } // send data if (writer != null) { // conn.setChunkedStreamingMode((64 * 1024) - 1); OutputStream connOut = null; connOut = conn.getOutputStream(); OutputStream out = new BufferedOutputStream(connOut, BUFFER_SIZE); writer.write(out); out.flush(); } // connect conn.connect(); // get stream, if present int respCode = conn.getResponseCode(); InputStream inputStream = null; if ((respCode == HttpStatus.SC_OK) || (respCode == HttpStatus.SC_CREATED) || (respCode == HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION) || (respCode == HttpStatus.SC_PARTIAL_CONTENT)) { inputStream = conn.getInputStream(); } // get the response return new Response(respCode, conn.getResponseMessage(), conn.getHeaderFields(), inputStream, conn.getErrorStream()); } catch (Exception e) { throw new CmisConnectionException("Cannot access " + url + ": " + e.getMessage(), e); } }
From source file:J2MEMixedRecordEnumerationExample.java
public void commandAction(Command command, Displayable displayable) { if (command == exit) { destroyApp(true);//ww w .jav a2 s.c o m notifyDestroyed(); } else if (command == start) { try { recordstore = RecordStore.openRecordStore("myRecordStore", true); byte[] outputRecord; String outputString[] = { "First Record", "Second Record", "Third Record" }; int outputInteger[] = { 15, 10, 5 }; boolean outputBoolean[] = { true, false, true }; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); DataOutputStream outputDataStream = new DataOutputStream(outputStream); for (int x = 0; x < 3; x++) { outputDataStream.writeUTF(outputString[x]); outputDataStream.writeBoolean(outputBoolean[x]); outputDataStream.writeInt(outputInteger[x]); outputDataStream.flush(); outputRecord = outputStream.toByteArray(); recordstore.addRecord(outputRecord, 0, outputRecord.length); } outputStream.reset(); outputStream.close(); outputDataStream.close(); StringBuffer buffer = new StringBuffer(); byte[] byteInputData = new byte[300]; ByteArrayInputStream inputStream = new ByteArrayInputStream(byteInputData); DataInputStream inputDataStream = new DataInputStream(inputStream); recordEnumeration = recordstore.enumerateRecords(null, null, false); while (recordEnumeration.hasNextElement()) { recordstore.getRecord(recordEnumeration.nextRecordId(), byteInputData, 0); buffer.append(inputDataStream.readUTF()); buffer.append("\n"); buffer.append(inputDataStream.readBoolean()); buffer.append("\n"); buffer.append(inputDataStream.readInt()); buffer.append("\n"); alert = new Alert("Reading", buffer.toString(), null, AlertType.WARNING); alert.setTimeout(Alert.FOREVER); display.setCurrent(alert); } inputStream.close(); recordstore.closeRecordStore(); if (RecordStore.listRecordStores() != null) { RecordStore.deleteRecordStore("myRecordStore"); recordEnumeration.destroy(); } } catch (Exception error) { alert = new Alert("Error Removing", error.toString(), null, AlertType.WARNING); alert.setTimeout(Alert.FOREVER); display.setCurrent(alert); } } }
From source file:com.photon.phresco.plugin.commons.PluginUtils.java
private void writeXml(String encrStr, String fileName) throws PhrescoException { DataOutputStream dos = null; FileOutputStream fos = null;/*www. j a v a 2 s . c o m*/ try { fos = new FileOutputStream(fileName); dos = new DataOutputStream(fos); dos.writeBytes(encrStr); } catch (FileNotFoundException e) { throw new PhrescoException(e); } catch (IOException e) { throw new PhrescoException(e); } finally { try { if (dos != null) { dos.close(); } if (fos != null) { fos.close(); } } catch (IOException e) { throw new PhrescoException(e); } } }