List of usage examples for java.io DataOutputStream write
public synchronized void write(int b) throws IOException
b
) to the underlying output stream. From source file:org.akita.io.HttpInvoker.java
/** * post with files using URLConnection Impl * @param actionUrl URL to post//from ww w .ja va 2 s .c om * @param params params to post * @param files files to post, support multi-files * @return response in String format * @throws IOException */ public static String postWithFilesUsingURLConnection(String actionUrl, ArrayList<NameValuePair> params, Map<String, File> files) throws AkInvokeException { try { Log.v(TAG, "post:" + actionUrl); if (params != null) { Log.v(TAG, "params:====================="); for (NameValuePair nvp : params) { Log.v(TAG, nvp.getName() + "=" + nvp.getValue()); } Log.v(TAG, "params end:====================="); } String BOUNDARY = java.util.UUID.randomUUID().toString(); String PREFIX = "--", LINEND = "\r\n"; String MULTIPART_FROM_DATA = "multipart/form-data"; String CHARSET = "UTF-8"; URL uri = new URL(actionUrl); HttpURLConnection conn = (HttpURLConnection) uri.openConnection(); conn.setReadTimeout(60 * 1000); conn.setDoInput(true); // permit input conn.setDoOutput(true); // permit output conn.setUseCaches(false); conn.setRequestMethod("POST"); // Post Method conn.setRequestProperty("connection", "keep-alive"); conn.setRequestProperty("Charsert", "UTF-8"); conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY); // firstly string params to add StringBuilder sb = new StringBuilder(); for (NameValuePair nameValuePair : params) { sb.append(PREFIX); sb.append(BOUNDARY); sb.append(LINEND); sb.append("Content-Disposition: form-data; name=\"" + nameValuePair.getName() + "\"" + LINEND); sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND); sb.append("Content-Transfer-Encoding: 8bit" + LINEND); sb.append(LINEND); sb.append(nameValuePair.getValue()); sb.append(LINEND); } DataOutputStream outStream = new DataOutputStream(conn.getOutputStream()); outStream.write(sb.toString().getBytes()); // send files secondly if (files != null) { int num = 0; for (Map.Entry<String, File> file : files.entrySet()) { num++; if (file.getKey() == null || file.getValue() == null) continue; else { if (!file.getValue().exists()) { throw new AkInvokeException(AkInvokeException.CODE_FILE_NOT_FOUND, "The file to upload is not found."); } } StringBuilder sb1 = new StringBuilder(); sb1.append(PREFIX); sb1.append(BOUNDARY); sb1.append(LINEND); sb1.append("Content-Disposition: form-data; name=\"" + file.getKey() + "\"; filename=\"" + file.getKey() + "\"" + LINEND); sb1.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINEND); sb1.append(LINEND); outStream.write(sb1.toString().getBytes()); InputStream is = new FileInputStream(file.getValue()); byte[] buffer = new byte[1024]; int len = 0; while ((len = is.read(buffer)) != -1) { outStream.write(buffer, 0, len); } is.close(); outStream.write(LINEND.getBytes()); } } // request end flag byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes(); outStream.write(end_data); outStream.flush(); // get response code int res = conn.getResponseCode(); InputStream in = conn.getInputStream(); StringBuilder sb2 = new StringBuilder(); if (res == 200) { BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8"), 8192); String line = null; while ((line = reader.readLine()) != null) { sb2.append(line + "\n"); } reader.close(); } outStream.close(); conn.disconnect(); Log.v(TAG, "response:" + sb2.toString()); return sb2.toString(); } catch (IOException ioe) { throw new AkInvokeException(AkInvokeException.CODE_IO_EXCEPTION, "IO Exception", ioe); } }
From source file:com.bcmcgroup.flare.client.ClientUtil.java
/** * Sends an HTTPS POST request and returns the response * * @param conn the HTTPS connection object * @param payload the payload for the POST request * @return the response from the remote server * *//*from w w w .jav a2s .c o m*/ public static int sendPost(HttpsURLConnection conn, String payload) { OutputStream outputStream = null; DataOutputStream wr = null; InputStream is = null; int response = 0; logger.debug("Attempting HTTPS POST..."); try { outputStream = conn.getOutputStream(); wr = new DataOutputStream(outputStream); wr.write(payload.getBytes("UTF-8")); wr.flush(); is = conn.getInputStream(); response = conn.getResponseCode(); } catch (IOException e) { logger.debug("IOException when attempting to send a post message. "); } finally { if (is != null) { try { is.close(); } catch (IOException e) { logger.debug("IOException when attempting to close an input stream. "); } } if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { logger.debug("IOException when attempting to close an output stream. "); } } if (wr != null) { try { wr.close(); } catch (IOException e) { logger.debug("IOException when attempting to close a data output stream. "); } } } logger.debug("HTTPS POST Response: " + response); return response; }
From source file:com.bcmcgroup.flare.client.ClientUtil.java
/** * Sends an HTTPS POST request and returns the response in String format * * @param conn the HTTPS connection object * @param payload the payload for the POST request * @return the response from the remote server in String format * *//* w ww.j a va2 s . co m*/ public static String sendPostGetStringResponse(HttpsURLConnection conn, String payload) { OutputStream outputStream = null; DataOutputStream wr = null; InputStream is = null; String response = ""; logger.debug("Attempting HTTPS POST"); try { outputStream = conn.getOutputStream(); wr = new DataOutputStream(outputStream); wr.write(payload.getBytes("UTF-8")); wr.flush(); is = conn.getInputStream(); response = IOUtils.toString(is, "UTF-8"); } catch (IOException e) { logger.debug("IOException when attempting to send a post message. "); } finally { if (is != null) { try { is.close(); } catch (IOException e) { logger.debug("IOException when attempting to close an input stream. "); } } if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { logger.debug("IOException when attempting to close an output stream. "); } } if (wr != null) { try { wr.close(); } catch (IOException e) { logger.debug("IOException when attempting to close a data output stream. "); } } } return response; }
From source file:org.apache.hive.hcatalog.streaming.mutate.client.AcidTableSerializer.java
/** Returns a base 64 encoded representation of the supplied {@link AcidTable}. */ public static String encode(AcidTable table) throws IOException { DataOutputStream data = null; ByteArrayOutputStream bytes = new ByteArrayOutputStream(); try {// w w w .j a va 2 s. c om data = new DataOutputStream(bytes); data.writeUTF(table.getDatabaseName()); data.writeUTF(table.getTableName()); data.writeBoolean(table.createPartitions()); if (table.getTransactionId() <= 0) { LOG.warn("Transaction ID <= 0. The recipient is probably expecting a transaction ID."); } data.writeLong(table.getTransactionId()); data.writeByte(table.getTableType().getId()); Table metaTable = table.getTable(); if (metaTable != null) { byte[] thrift = new TSerializer(new TCompactProtocol.Factory()).serialize(metaTable); data.writeInt(thrift.length); data.write(thrift); } else { LOG.warn("Meta store table is null. The recipient is probably expecting an instance."); data.writeInt(0); } } catch (TException e) { throw new IOException("Error serializing meta store table.", e); } finally { data.close(); } return PROLOG_V1 + new String(Base64.encodeBase64(bytes.toByteArray()), Charset.forName("UTF-8")); }
From source file:com.hippo.httpclient.JsonPoster.java
@Override public void onOutput(HttpURLConnection conn) throws Exception { super.onOutput(conn); DataOutputStream out = new DataOutputStream(conn.getOutputStream()); out.write(mJSON.toString().getBytes("utf-8")); out.flush();//from ww w. ja v a 2s. c om out.close(); }
From source file:CounterApp.java
public int getCount() throws Exception { java.net.URL url = new java.net.URL(servletURL); java.net.URLConnection con = url.openConnection(); if (sessionCookie != null) { con.setRequestProperty("cookie", sessionCookie); }/*from w ww .j a va 2s .c o m*/ con.setUseCaches(false); con.setDoOutput(true); con.setDoInput(true); ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); DataOutputStream out = new DataOutputStream(byteOut); out.flush(); byte buf[] = byteOut.toByteArray(); con.setRequestProperty("Content-type", "application/octet-stream"); con.setRequestProperty("Content-length", "" + buf.length); DataOutputStream dataOut = new DataOutputStream(con.getOutputStream()); dataOut.write(buf); dataOut.flush(); dataOut.close(); DataInputStream in = new DataInputStream(con.getInputStream()); int count = in.readInt(); in.close(); if (sessionCookie == null) { String cookie = con.getHeaderField("set-cookie"); if (cookie != null) { sessionCookie = parseCookie(cookie); System.out.println("Setting session ID=" + sessionCookie); } } return count; }
From source file:dualcontrol.CryptoClientDemo.java
private void call(Properties properties, MockableConsole console, String hostAddress, int port, byte[] data) throws Exception { Socket socket = SSLContexts.create(false, "cryptoclient.ssl", properties, console).getSocketFactory() .createSocket(hostAddress, port); DataOutputStream dos = new DataOutputStream(socket.getOutputStream()); dos.writeShort(data.length);//from w ww . j a va 2 s . c om dos.write(data); dos.flush(); DataInputStream dis = new DataInputStream(socket.getInputStream()); byte[] ivBytes = new byte[dis.readShort()]; dis.readFully(ivBytes); byte[] bytes = new byte[dis.readShort()]; dis.readFully(bytes); if (new String(data).contains("DECRYPT")) { System.err.printf("INFO CryptoClientDemo decrypted %s\n", new String(bytes)); } else { System.out.printf("%s:%s\n", Base64.encodeBase64String(ivBytes), Base64.encodeBase64String(bytes)); } socket.close(); }
From source file:org.apache.hadoop.tools.distcp2.mapred.TestCopyMapper.java
private static void touchFile(String path) throws Exception { FileSystem fs;// ww w . jav a 2s . c om DataOutputStream outputStream = null; try { fs = cluster.getFileSystem(); final Path qualifiedPath = new Path(path).makeQualified(fs.getUri(), fs.getWorkingDirectory()); final long blockSize = fs.getDefaultBlockSize() * 2; outputStream = fs.create(qualifiedPath, true, 0, (short) (fs.getDefaultReplication() * 2), blockSize); outputStream.write(new byte[FILE_SIZE]); pathList.add(qualifiedPath); ++nFiles; FileStatus fileStatus = fs.getFileStatus(qualifiedPath); System.out.println(fileStatus.getBlockSize()); System.out.println(fileStatus.getReplication()); } finally { IOUtils.cleanup(null, outputStream); } }
From source file:org.apache.hadoop.tools.mapred.filechunk.TestCopyChunkMapper.java
private static void touchFile(String path, boolean createMultipleBlocks, ChecksumOpt checksumOpt) throws Exception { FileSystem fs;/*from w w w . ja v a 2 s .co m*/ DataOutputStream outputStream = null; try { fs = cluster.getFileSystem(); final Path qualifiedPath = new Path(path).makeQualified(fs.getUri(), fs.getWorkingDirectory()); final long blockSize = createMultipleBlocks ? NON_DEFAULT_BLOCK_SIZE : fs.getDefaultBlockSize(qualifiedPath) * 2; FsPermission permission = FsPermission.getFileDefault().applyUMask(FsPermission.getUMask(fs.getConf())); outputStream = fs.create(qualifiedPath, permission, EnumSet.of(CreateFlag.CREATE, CreateFlag.OVERWRITE), 0, (short) (fs.getDefaultReplication(qualifiedPath) * 2), blockSize, null, checksumOpt); byte[] bytes = new byte[DEFAULT_FILE_SIZE]; outputStream.write(bytes); long fileSize = DEFAULT_FILE_SIZE; if (createMultipleBlocks) { while (fileSize < 2 * blockSize) { outputStream.write(bytes); outputStream.flush(); fileSize += DEFAULT_FILE_SIZE; } } pathList.add(qualifiedPath); ++nFiles; FileStatus fileStatus = fs.getFileStatus(qualifiedPath); System.out.println(fileStatus.getBlockSize()); System.out.println(fileStatus.getReplication()); } finally { IOUtils.cleanup(null, outputStream); } }
From source file:ai.eve.volley.request.JsonRequest.java
@Override public void getBody(HttpURLConnection connection) { try {/* ww w. j a va 2 s. co m*/ if (mRequestBody != null) { connection.setDoOutput(true); connection.addRequestProperty(HTTP.CONTENT_TYPE, getBodyContentType()); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(mRequestBody.getBytes(PROTOCOL_CHARSET)); out.close(); } } catch (UnsupportedEncodingException uee) { NetroidLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", mRequestBody, PROTOCOL_CHARSET); } catch (IOException e) { e.printStackTrace(); } }