List of usage examples for java.net HttpURLConnection setFixedLengthStreamingMode
public void setFixedLengthStreamingMode(long contentLength)
From source file:lucee.commons.io.res.type.s3.S3.java
public HttpURLConnection preput(String bucketName, String objectName, int acl, String contentType) throws IOException, InvalidKeyException, NoSuchAlgorithmException { bucketName = checkBucket(bucketName); objectName = checkObjectName(objectName); String dateTimeString = Util.toHTTPTimeString(); // Create a canonical string to send based on operation requested String cs = "PUT\n\n" + contentType + "\n" + dateTimeString + "\nx-amz-acl:" + toStringACL(acl) + "\n/" + bucketName + "/" + objectName; String signature = createSignature(cs, getSecretAccessKeyValidate(), "iso-8859-1"); String strUrl = "http://" + bucketName + "." + host + "/" + objectName; if (Util.hasUpperCase(bucketName)) strUrl = "http://" + host + "/" + bucketName + "/" + objectName; URL url = new URL(strUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("PUT"); conn.setFixedLengthStreamingMode(227422142); conn.setDoOutput(true);/* www.ja va 2s .c o m*/ conn.setUseCaches(false); conn.setRequestProperty("CONTENT-TYPE", contentType); conn.setRequestProperty("USER-AGENT", "S3 Resource"); //conn.setRequestProperty("Transfer-Encoding", "chunked" ); conn.setRequestProperty("Date", dateTimeString); conn.setRequestProperty("x-amz-acl", toStringACL(acl)); conn.setRequestProperty("Authorization", "AWS " + getAccessKeyIdValidate() + ":" + signature); return conn; }
From source file:dk.itst.oiosaml.sp.service.util.HttpSOAPClient.java
public Envelope wsCall(String location, String username, String password, boolean ignoreCertPath, String xml, String soapAction) throws IOException, SOAPException { URI serviceLocation;//w w w .j av a 2 s . com try { serviceLocation = new URI(location); } catch (URISyntaxException e) { throw new IOException("Invalid uri for artifact resolve: " + location); } if (log.isDebugEnabled()) log.debug("serviceLocation..:" + serviceLocation); if (log.isDebugEnabled()) log.debug("SOAP Request: " + xml); HttpURLConnection c = (HttpURLConnection) serviceLocation.toURL().openConnection(); if (c instanceof HttpsURLConnection) { HttpsURLConnection sc = (HttpsURLConnection) c; if (ignoreCertPath) { sc.setSSLSocketFactory(new DummySSLSocketFactory()); sc.setHostnameVerifier(new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }); } } c.setAllowUserInteraction(false); c.setDoInput(true); c.setDoOutput(true); c.setFixedLengthStreamingMode(xml.getBytes("UTF-8").length); c.setRequestMethod("POST"); c.setReadTimeout(20000); c.setConnectTimeout(30000); addContentTypeHeader(xml, c); c.addRequestProperty("SOAPAction", "\"" + (soapAction == null ? "" : soapAction) + "\""); if (username != null && password != null) { c.addRequestProperty("Authorization", "Basic " + Base64.encodeBytes((username + ":" + password).getBytes(), Base64.DONT_BREAK_LINES)); } OutputStream outputStream = c.getOutputStream(); IOUtils.write(xml, outputStream, "UTF-8"); outputStream.flush(); outputStream.close(); if (c.getResponseCode() == 200) { InputStream inputStream = c.getInputStream(); String result = IOUtils.toString(inputStream, "UTF-8"); inputStream.close(); if (log.isDebugEnabled()) log.debug("Server SOAP response: " + result); XMLObject res = SAMLUtil.unmarshallElementFromString(result); Envelope envelope = (Envelope) res; if (SAMLUtil.getFirstElement(envelope.getBody(), Fault.class) != null) { log.warn( "Result has soap11:Fault, but server returned 200 OK. Treating as error, please fix the server"); throw new SOAPException(c.getResponseCode(), result); } return envelope; } else { log.debug("Response code: " + c.getResponseCode()); InputStream inputStream = c.getErrorStream(); String result = IOUtils.toString(inputStream, "UTF-8"); inputStream.close(); if (log.isDebugEnabled()) log.debug("Server SOAP fault: " + result); throw new SOAPException(c.getResponseCode(), result); } }
From source file:org.jboss.arquillian.container.tomcat.CommonTomcatManager.java
/** * Execute the specified command, based on the configured properties. The input stream will be closed upon completion of * this task, whether it was executed successfully or not. * * @param command Command to be executed * @param istream InputStream to include in an HTTP PUT, if any * @param contentType Content type to specify for the input, if any * @param contentLength Content length to specify for the input, if any * @throws IOException/*from w w w . j a v a 2s .c o m*/ * @throws MalformedURLException * @throws DeploymentException */ protected void execute(String command, InputStream istream, String contentType, int contentLength) throws IOException { URLConnection conn = null; try { // Create a connection for this command conn = (new URL(configuration.getManagerUrl() + command)).openConnection(); HttpURLConnection hconn = (HttpURLConnection) conn; // Set up standard connection characteristics hconn.setAllowUserInteraction(false); hconn.setDoInput(true); hconn.setUseCaches(false); if (istream != null) { hconn.setDoOutput(true); hconn.setRequestMethod("PUT"); if (contentType != null) { hconn.setRequestProperty("Content-Type", contentType); } if (contentLength >= 0) { hconn.setRequestProperty("Content-Length", "" + contentLength); hconn.setFixedLengthStreamingMode(contentLength); } } else { hconn.setDoOutput(false); hconn.setRequestMethod("GET"); } hconn.setRequestProperty("User-Agent", "Arquillian-Tomcat-Manager-Util/1.0"); // add authorization header if password is provided if (configuration.getUser() != null && configuration.getUser().length() != 0) { hconn.setRequestProperty("Authorization", constructHttpBasicAuthHeader()); } hconn.setRequestProperty("Accept", "text/plain"); // Establish the connection with the server hconn.connect(); // Send the request data (if any) if (istream != null) { BufferedOutputStream ostream = new BufferedOutputStream(hconn.getOutputStream(), 1024); IOUtil.copy(istream, ostream); ostream.flush(); ostream.close(); istream.close(); } processResponse(command, hconn); } finally { IOUtil.closeQuietly(istream); } }
From source file:im.vector.util.BugReporter.java
/** * Send a bug report./*from w ww . j av a 2s .c om*/ * * @param context the application context * @param withDevicesLogs true to include the device logs * @param withCrashLogs true to include the crash logs */ private static void sendBugReport(final Context context, final boolean withDevicesLogs, final boolean withCrashLogs, final String bugDescription, final IMXBugReportListener listener) { new AsyncTask<Void, Integer, String>() { @Override protected String doInBackground(Void... voids) { File bugReportFile = new File(context.getApplicationContext().getFilesDir(), "bug_report"); if (bugReportFile.exists()) { bugReportFile.delete(); } String serverError = null; FileWriter fileWriter = null; try { fileWriter = new FileWriter(bugReportFile); JsonWriter jsonWriter = new JsonWriter(fileWriter); jsonWriter.beginObject(); // android bug report jsonWriter.name("user_agent").value("Android"); // logs list jsonWriter.name("logs"); jsonWriter.beginArray(); // the logs are optional if (withDevicesLogs) { List<File> files = org.matrix.androidsdk.util.Log.addLogFiles(new ArrayList<File>()); for (File f : files) { if (!mIsCancelled) { jsonWriter.beginObject(); jsonWriter.name("lines").value(convertStreamToString(f)); jsonWriter.endObject(); jsonWriter.flush(); } } } if (!mIsCancelled && (withCrashLogs || withDevicesLogs)) { jsonWriter.beginObject(); jsonWriter.name("lines").value(getLogCatError()); jsonWriter.endObject(); jsonWriter.flush(); } jsonWriter.endArray(); jsonWriter.name("text").value(bugDescription); String version = ""; if (null != Matrix.getInstance(context).getDefaultSession()) { version += "User : " + Matrix.getInstance(context).getDefaultSession().getMyUserId() + "\n"; } version += "Phone : " + Build.MODEL.trim() + " (" + Build.VERSION.INCREMENTAL + " " + Build.VERSION.RELEASE + " " + Build.VERSION.CODENAME + ")\n"; version += "Vector version: " + Matrix.getInstance(context).getVersion(true) + "\n"; version += "SDK version: " + Matrix.getInstance(context).getDefaultSession().getVersion(true) + "\n"; version += "Olm version: " + Matrix.getInstance(context).getDefaultSession().getCryptoVersion(context, true) + "\n"; jsonWriter.name("version").value(version); jsonWriter.endObject(); jsonWriter.close(); } catch (Exception e) { Log.e(LOG_TAG, "doInBackground ; failed to collect the bug report data " + e.getMessage()); serverError = e.getLocalizedMessage(); } catch (OutOfMemoryError oom) { Log.e(LOG_TAG, "doInBackground ; failed to collect the bug report data " + oom.getMessage()); serverError = oom.getMessage(); if (TextUtils.isEmpty(serverError)) { serverError = "Out of memory"; } } try { if (null != fileWriter) { fileWriter.close(); } } catch (Exception e) { Log.e(LOG_TAG, "doInBackground ; failed to close fileWriter " + e.getMessage()); } if (TextUtils.isEmpty(serverError) && !mIsCancelled) { // the screenshot is defined here // File screenFile = new File(VectorApp.mLogsDirectoryFile, "screenshot.jpg"); InputStream inputStream = null; HttpURLConnection conn = null; try { inputStream = new FileInputStream(bugReportFile); final int dataLen = inputStream.available(); // should never happen if (0 == dataLen) { return "No data"; } URL url = new URL(context.getResources().getString(R.string.bug_report_url)); conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Content-Length", Integer.toString(dataLen)); // avoid caching data before really sending them. conn.setFixedLengthStreamingMode(inputStream.available()); conn.connect(); DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); byte[] buffer = new byte[8192]; // read file and write it into form... int bytesRead; int totalWritten = 0; while (!mIsCancelled && (bytesRead = inputStream.read(buffer, 0, buffer.length)) > 0) { dos.write(buffer, 0, bytesRead); totalWritten += bytesRead; publishProgress(totalWritten * 100 / dataLen); } dos.flush(); dos.close(); int mResponseCode; try { // Read the SERVER RESPONSE mResponseCode = conn.getResponseCode(); } catch (EOFException eofEx) { mResponseCode = HttpURLConnection.HTTP_INTERNAL_ERROR; } // if the upload failed, try to retrieve the reason if (mResponseCode != HttpURLConnection.HTTP_OK) { serverError = null; InputStream is = conn.getErrorStream(); if (null != is) { int ch; StringBuilder b = new StringBuilder(); while ((ch = is.read()) != -1) { b.append((char) ch); } serverError = b.toString(); is.close(); // check if the error message try { JSONObject responseJSON = new JSONObject(serverError); serverError = responseJSON.getString("error"); } catch (JSONException e) { Log.e(LOG_TAG, "doInBackground ; Json conversion failed " + e.getMessage()); } // should never happen if (null == serverError) { serverError = "Failed with error " + mResponseCode; } is.close(); } } } catch (Exception e) { Log.e(LOG_TAG, "doInBackground ; failed with error " + e.getClass() + " - " + e.getMessage()); serverError = e.getLocalizedMessage(); if (TextUtils.isEmpty(serverError)) { serverError = "Failed to upload"; } } catch (OutOfMemoryError oom) { Log.e(LOG_TAG, "doInBackground ; failed to send the bug report " + oom.getMessage()); serverError = oom.getLocalizedMessage(); if (TextUtils.isEmpty(serverError)) { serverError = "Out ouf memory"; } } finally { try { if (null != conn) { conn.disconnect(); } } catch (Exception e2) { Log.e(LOG_TAG, "doInBackground : conn.disconnect() failed " + e2.getMessage()); } } if (null != inputStream) { try { inputStream.close(); } catch (Exception e) { Log.e(LOG_TAG, "doInBackground ; failed to close the inputStream " + e.getMessage()); } } } return serverError; } @Override protected void onProgressUpdate(Integer... progress) { super.onProgressUpdate(progress); if (null != listener) { try { listener.onProgress((null == progress) ? 0 : progress[0]); } catch (Exception e) { Log.e(LOG_TAG, "## onProgress() : failed " + e.getMessage()); } } } @Override protected void onPostExecute(String reason) { if (null != listener) { try { if (mIsCancelled) { listener.onUploadCancelled(); } else if (null == reason) { listener.onUploadSucceed(); } else { listener.onUploadFailed(reason); } } catch (Exception e) { Log.e(LOG_TAG, "## onPostExecute() : failed " + e.getMessage()); } } } }.execute(); }
From source file:com.vimeo.VimeoUploadClient.java
/** * upload file (streaming)//from w w w .j a va 2 s . c om * * @param endpoint */ private void doPut(String endpoint) { URL endpointUrl; HttpURLConnection connection; try { endpointUrl = new URL(endpoint); connection = (HttpURLConnection) endpointUrl.openConnection(); connection.setRequestMethod("PUT"); connection.setRequestProperty("Content-Length", videoFile.length() + ""); connection.setRequestProperty("Content-Type", new MimetypesFileTypeMap().getContentType(videoFile)); connection.setFixedLengthStreamingMode((int) videoFile.length()); connection.setDoOutput(true); CopyStreamListener listener = new CopyStreamListener() { public void bytesTransferred(long totalBytesTransferred, int bytesTransferred, long streamSize) { // TODO: get the values to visualize it: currentStreamSize, // currentBytesTransferred currentStreamSize = streamSize; currentBytesTransferred = totalBytesTransferred; /* * System.out.printf("\r%-30S: %d / %d (%d %%)", "Sent", * totalBytesTransferred, streamSize, totalBytesTransferred * * 100 / streamSize); */ } public void bytesTransferred(CopyStreamEvent event) { } }; InputStream in = new FileInputStream(videoFile); OutputStream out = connection.getOutputStream(); System.out.println("Uploading \"" + videoFile.getAbsolutePath() + "\"... "); long c = Util.copyStream(in, out, Util.DEFAULT_COPY_BUFFER_SIZE, videoFile.length(), listener); System.out.printf("\n%-30S: %d\n", "Bytes sent", c); in.close(); out.close(); // return code System.out.printf("\n%-30S: %d\n", "Response code", connection.getResponseCode()); // TODO: Response code, if everything OK the code is 200 } catch (Exception e) { e.printStackTrace(); } }
From source file:de.fu_berlin.inf.dpp.netbeans.feedback.FileSubmitter.java
/** * Tries to upload the given file to the given HTTP server (via POST * method)./*w w w . j av a2 s .c o m*/ * * @param file * the file to upload * @param url * the URL of the server, that is supposed to handle the file * @param monitor * a monitor to report progress to * @throws IOException * if an I/O error occurs * */ public static void uploadFile(final File file, final String url, IProgressMonitor monitor) throws IOException { final String CRLF = "\r\n"; final String doubleDash = "--"; final String boundary = generateBoundary(); HttpURLConnection connection = null; OutputStream urlConnectionOut = null; FileInputStream fileIn = null; if (monitor == null) monitor = new NullProgressMonitor(); int contentLength = (int) file.length(); if (contentLength == 0) { log.warn("file size of file " + file.getAbsolutePath() + " is 0 or the file does not exist"); return; } monitor.beginTask("Uploading file " + file.getName(), contentLength); try { URL connectionURL = new URL(url); if (!"http".equals(connectionURL.getProtocol())) throw new IOException("only HTTP protocol is supported"); connection = (HttpURLConnection) connectionURL.openConnection(); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setReadTimeout(TIMEOUT); connection.setConnectTimeout(TIMEOUT); connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); String contentDispositionLine = "Content-Disposition: form-data; name=\"" + file.getName() + "\"; filename=\"" + file.getName() + "\"" + CRLF; String contentTypeLine = "Content-Type: application/octet-stream; charset=ISO-8859-1" + CRLF; String contentTransferEncoding = "Content-Transfer-Encoding: binary" + CRLF; contentLength += 2 * boundary.length() + contentDispositionLine.length() + contentTypeLine.length() + contentTransferEncoding.length() + 4 * CRLF.length() + 3 * doubleDash.length(); connection.setFixedLengthStreamingMode(contentLength); connection.connect(); urlConnectionOut = connection.getOutputStream(); PrintWriter writer = new PrintWriter(new OutputStreamWriter(urlConnectionOut, "US-ASCII"), true); writer.append(doubleDash).append(boundary).append(CRLF); writer.append(contentDispositionLine); writer.append(contentTypeLine); writer.append(contentTransferEncoding); writer.append(CRLF); writer.flush(); fileIn = new FileInputStream(file); byte[] buffer = new byte[8192]; for (int read = 0; (read = fileIn.read(buffer)) > 0;) { if (monitor.isCanceled()) return; urlConnectionOut.write(buffer, 0, read); monitor.worked(read); } urlConnectionOut.flush(); writer.append(CRLF); writer.append(doubleDash).append(boundary).append(doubleDash).append(CRLF); writer.close(); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { log.debug("uploaded file " + file.getAbsolutePath() + " to " + connectionURL.getHost()); return; } throw new IOException("failed to upload file " + file.getAbsolutePath() + connectionURL.getHost() + " [" + connection.getResponseMessage() + "]"); } finally { IOUtils.closeQuietly(fileIn); IOUtils.closeQuietly(urlConnectionOut); if (connection != null) connection.disconnect(); monitor.done(); } }
From source file:com.amazonaws.http.UrlHttpClient.java
/** * Writes the content (if any) of the request to the passed connection * * @param request/* w w w .j a v a 2s .co m*/ * @param connection * @param curlBuilder * @throws IOException */ void writeContentToConnection(final HttpRequest request, final HttpURLConnection connection, final CurlBuilder curlBuilder) throws IOException { // Note: if DoOutput is set to true and method is GET, HttpUrlConnection // will silently change the method to POST. if (request.getContent() != null && request.getContentLength() >= 0) { connection.setDoOutput(true); // This is for backward compatibility, because // setFixedLengthStreamingMode(long) is available in API level 19. if (!request.isStreaming()) { connection.setFixedLengthStreamingMode((int) request.getContentLength()); } final OutputStream os = connection.getOutputStream(); ByteBuffer curlBuffer = null; if (curlBuilder != null) { if (request.getContentLength() < Integer.MAX_VALUE) { curlBuffer = ByteBuffer.allocate((int) request.getContentLength()); } else { curlBuilder.setContentOverflow(true); } } write(request.getContent(), os, curlBuilder, curlBuffer); if (curlBuilder != null && curlBuffer != null && curlBuffer.position() != 0) { // has content curlBuilder.setContent(new String(curlBuffer.array(), "UTF-8")); } os.flush(); os.close(); } }
From source file:ru.runa.wf.logic.bot.WebServiceTaskHandler.java
/** * Opens HTTP connection to web service and setup required connection * parameters. Send request to web service. * //from w w w .j a va2s . c o m * @param url * URL to open connection. * @param length * SOAP data length. * @return HTTP connection to communicate with web service. */ private HttpURLConnection sendRequest(URL url, byte[] soapData) throws Exception { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Content-Type", "text/xml; charset=" + settings.encoding); if (settings.authBase != null) { String auth = Base64.encodeBase64String(settings.authBase.getBytes()); connection.setRequestProperty("Authorization", "Basic " + auth); } String soapAction = settings.soapAction == null ? "" : settings.soapAction; connection.setRequestProperty("SOAPAction", "\"" + soapAction + "\""); if (settings.requestMethod != null) { connection.setRequestMethod(settings.requestMethod); } connection.setFixedLengthStreamingMode(soapData.length); connection.setDoOutput(true); OutputStream os = connection.getOutputStream(); os.write(soapData); os.flush(); return connection; }
From source file:us.camin.api.Server.java
public JSONObject exec(String path, String method, HashMap<String, String> params) throws MalformedURLException, ProtocolException, IOException { HttpURLConnection conn = open(path); conn.setRequestMethod(method);//from w ww . jav a 2 s .c o m if (params.size() > 0) { conn.setDoOutput(true); Set<Map.Entry<String, String>> values = params.entrySet(); Iterator<Map.Entry<String, String>> it = values.iterator(); StringBuilder sb = new StringBuilder(); while (it.hasNext()) { Map.Entry<String, String> param = it.next(); sb.append(URLEncoder.encode(param.getKey(), "UTF-8")); sb.append("="); sb.append(URLEncoder.encode(param.getValue(), "UTF-8")); sb.append("&"); } String postData = sb.substring(0, sb.length() - 1); conn.setFixedLengthStreamingMode(postData.length()); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); DataOutputStream out = new DataOutputStream(conn.getOutputStream()); out.writeBytes(postData); } JSONObject ret = readJSON(conn); conn.disconnect(); return ret; }
From source file:org.restcomm.app.utillib.Reporters.WebReporter.WebReporter.java
/** * Uses the json packet supplied as the arguments to call the web service defined by the * <code>endpoint</code> supplied. The response is returned as a string that is expected to be parsed * later (as a json packet).// w ww .j av a 2s . com * @param endpoint * @param jsonPacket * @param log whether to log the <code>jsonPacket</code> to {@link LoggerUtil#LOG_FILE} * @return */ private String sendJSONPacket(String endpoint, String jsonPacket, boolean log) throws Exception { URL url = new URL(endpoint); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10000); conn.setConnectTimeout(15000); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); conn.setFixedLengthStreamingMode(jsonPacket.getBytes().length); conn.setRequestProperty("Content-Type", "application/json; charset=utf-8"); conn.setRequestProperty("X-Requested-With", "XMLHttpRequest"); conn.setRequestProperty("MMCBrand", Global.getAppName(mContext)); conn.setRequestProperty("MMCVersion", Global.getString(mContext, "app_versionName")); LoggerUtil.logToFile(LoggerUtil.Level.DEBUG, TAG, "sendJSONPacket", url.toString()); //LoggerUtil.logToFile(LoggerUtil.Level.DEBUG, TAG, "sendJSONPacket json: ", jsonPacket); //open conn.connect(); OutputStream os = new BufferedOutputStream(conn.getOutputStream()); os.write(jsonPacket.getBytes()); //clean up os.flush(); String responseContents = readString(conn); return responseContents; }