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.brickred.socialauth.util.HttpUtil.java
/** * Makes HTTP request using java.net.HTTPURLConnection * //from ww w. j av a 2 s . co m * @param urlStr * the URL String * @param requestMethod * Method type * @param body * Body to pass in request. * @param header * Header parameters * @return Response Object * @throws SocialAuthException */ public static Response doHttpRequest(final String urlStr, final String requestMethod, final String body, final Map<String, String> header) throws SocialAuthException { HttpURLConnection conn; try { URL url = new URL(urlStr); if (proxyObj != null) { conn = (HttpURLConnection) url.openConnection(proxyObj); } else { conn = (HttpURLConnection) url.openConnection(); } if (MethodType.POST.toString().equalsIgnoreCase(requestMethod) || MethodType.PUT.toString().equalsIgnoreCase(requestMethod)) { conn.setDoOutput(true); } conn.setDoInput(true); conn.setInstanceFollowRedirects(true); if (timeoutValue > 0) { LOG.debug("Setting connection timeout : " + timeoutValue); conn.setConnectTimeout(timeoutValue); } if (requestMethod != null) { conn.setRequestMethod(requestMethod); } if (header != null) { for (String key : header.keySet()) { conn.setRequestProperty(key, header.get(key)); } } // If use POST or PUT must use this OutputStream os = null; if (body != null) { if (requestMethod != null && !MethodType.GET.toString().equals(requestMethod) && !MethodType.DELETE.toString().equals(requestMethod)) { os = conn.getOutputStream(); DataOutputStream out = new DataOutputStream(os); out.write(body.getBytes("UTF-8")); out.flush(); } } conn.connect(); } catch (Exception e) { throw new SocialAuthException(e); } return new Response(conn); }
From source file:HexUtil.java
/** * Write a (reasonably short) BigInteger to a stream. * @param integer the BigInteger to write * @param out the stream to write it to *//*from w w w . ja va 2s . co m*/ public static void writeBigInteger(BigInteger integer, DataOutputStream out) throws IOException { if (integer.signum() == -1) { //dump("Negative BigInteger", Logger.ERROR, true); throw new IllegalStateException("Negative BigInteger!"); } byte[] buf = integer.toByteArray(); if (buf.length > Short.MAX_VALUE) throw new IllegalStateException("Too long: " + buf.length); out.writeShort((short) buf.length); out.write(buf); }
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 .j a v a 2 s .com 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:Main.java
public static String uploadFile(File file, String RequestURL) { String BOUNDARY = UUID.randomUUID().toString(); String PREFIX = "--", LINE_END = "\r\n"; String CONTENT_TYPE = "multipart/form-data"; try {//from ww w .j av a2 s.c o m URL url = new URL(RequestURL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(TIME_OUT); conn.setConnectTimeout(TIME_OUT); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Charset", CHARSET); conn.setRequestProperty("connection", "keep-alive"); conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY); if (file != null) { OutputStream outputSteam = conn.getOutputStream(); DataOutputStream dos = new DataOutputStream(outputSteam); StringBuffer sb = new StringBuffer(); sb.append(PREFIX); sb.append(BOUNDARY); sb.append(LINE_END); sb.append("Content-Disposition: form-data; name=\"img\"; filename=\"" + file.getName() + "\"" + LINE_END); sb.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINE_END); sb.append(LINE_END); dos.write(sb.toString().getBytes()); InputStream is = new FileInputStream(file); byte[] bytes = new byte[1024]; int len = 0; while ((len = is.read(bytes)) != -1) { dos.write(bytes, 0, len); } is.close(); dos.write(LINE_END.getBytes()); byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes(); dos.write(end_data); dos.flush(); int res = conn.getResponseCode(); Log.e(TAG, "response code:" + res); if (res == 200) { return SUCCESS; } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return FAILURE; }
From source file:org.apache.rocketmq.tools.command.message.QueryMsgByIdSubCommand.java
private static String createBodyFile(MessageExt msg) throws IOException { DataOutputStream dos = null; try {/*from www . ja v a 2s.c o m*/ 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:org.alfresco.repo.web.scripts.tenant.TenantAdminSystemTest.java
private static String callInOutWeb(String urlString, String method, String ticket, String data, String contentType, String soapAction) throws MalformedURLException, URISyntaxException, IOException { URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod(method);//from w w w .java 2 s. c o m conn.setRequestProperty("Content-type", contentType); conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); if (soapAction != null) { conn.setRequestProperty("SOAPAction", soapAction); } if (ticket != null) { // add Base64 encoded authorization header // refer to: http://wiki.alfresco.com/wiki/Web_Scripts_Framework#HTTP_Basic_Authentication conn.addRequestProperty("Authorization", "Basic " + Base64.encodeBytes(ticket.getBytes())); } String result = null; BufferedReader br = null; DataOutputStream wr = null; OutputStream os = null; InputStream is = null; try { os = conn.getOutputStream(); wr = new DataOutputStream(os); wr.write(data.getBytes()); wr.flush(); } finally { if (wr != null) { wr.close(); } ; if (os != null) { os.close(); } ; } try { is = conn.getInputStream(); br = new BufferedReader(new InputStreamReader(is)); String line = null; StringBuffer sb = new StringBuffer(); while (((line = br.readLine()) != null)) { sb.append(line); } result = sb.toString(); } finally { if (br != null) { br.close(); } ; if (is != null) { is.close(); } ; } return result; }
From source file:com.flozano.socialauth.util.HttpUtil.java
/** * Makes HTTP request using java.net.HTTPURLConnection and optional settings * for the connection//from w w w .ja v a 2 s. c om * * @param urlStr * the URL String * @param requestMethod * Method type * @param body * Body to pass in request. * @param header * Header parameters * @param connectionSettings * The connection settings to apply * @return Response Object * @throws SocialAuthException */ public static Response doHttpRequest(final String urlStr, final String requestMethod, final String body, final Map<String, String> header, Optional<ConnectionSettings> connectionSettings) throws SocialAuthException { HttpURLConnection conn; try { URL url = new URL(urlStr); if (proxyObj != null) { conn = (HttpURLConnection) url.openConnection(proxyObj); } else { conn = (HttpURLConnection) url.openConnection(); } connectionSettings.ifPresent(settings -> settings.apply(conn)); if (MethodType.POST.toString().equalsIgnoreCase(requestMethod) || MethodType.PUT.toString().equalsIgnoreCase(requestMethod)) { conn.setDoOutput(true); } conn.setDoInput(true); conn.setInstanceFollowRedirects(true); if (timeoutValue > 0) { LOG.debug("Setting connection timeout : " + timeoutValue); conn.setConnectTimeout(timeoutValue); } if (requestMethod != null) { conn.setRequestMethod(requestMethod); } if (header != null) { for (String key : header.keySet()) { conn.setRequestProperty(key, header.get(key)); } } // If use POST or PUT must use this OutputStream os = null; if (body != null) { if (requestMethod != null && !MethodType.GET.toString().equals(requestMethod) && !MethodType.DELETE.toString().equals(requestMethod)) { os = conn.getOutputStream(); DataOutputStream out = new DataOutputStream(os); out.write(body.getBytes("UTF-8")); out.flush(); } } conn.connect(); } catch (Exception e) { throw new SocialAuthException(e); } return new Response(conn); }
From source file:org.apache.hadoop.tools.TestDistCp.java
private static void touchFile(String path) throws Exception { FileSystem fs;//from w w w. j a va 2s . c o m DataOutputStream outputStream = null; try { fs = cluster.getFileSystem(); final Path qualifiedPath = new Path(path).makeQualified(fs.getUri(), fs.getWorkingDirectory()); final long blockSize = fs.getDefaultBlockSize(new Path(path)) * 2; outputStream = fs.create(qualifiedPath, true, 0, (short) (fs.getDefaultReplication(new Path(path)) * 2), blockSize); outputStream.write(new byte[FILE_SIZE]); pathList.add(qualifiedPath); } finally { IOUtils.cleanup(null, outputStream); } }
From source file:com.dbay.apns4j.tools.ApnsTools.java
public final static byte[] generateData(List<FrameItem> list) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataOutputStream os = new DataOutputStream(bos); int frameLength = 0; for (FrameItem item : list) { // itemId length = 1, itemDataLength = 2 frameLength += 1 + 2 + item.getItemLength(); }/*w w w.jav a 2s . c om*/ try { os.writeByte(Command.SEND_V2); os.writeInt(frameLength); for (FrameItem item : list) { os.writeByte(item.getItemId()); os.writeShort(item.getItemLength()); os.write(item.getItemData()); } return bos.toByteArray(); } catch (IOException e) { e.printStackTrace(); } throw new RuntimeException(); }
From source file:com.alibaba.akita.io.HttpInvoker.java
/** * post with files using URLConnection Impl * @param actionUrl URL to post//from ww w . j a v a2 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 { 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" + num + "\"; 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(); return sb2.toString(); } catch (IOException ioe) { throw new AkInvokeException(AkInvokeException.CODE_IO_EXCEPTION, "IO Exception", ioe); } }