List of usage examples for java.io BufferedOutputStream flush
@Override public synchronized void flush() throws IOException
From source file:com.wso2telco.dep.mediator.RequestExecutor.java
/** */*from ww w .jav a 2s . c o m*/ * @param url * @param requestStr * @param messageContext * @return */ public String makeCreditRequest(OperatorEndpoint operatorendpoint, String url, String requestStr, boolean auth, MessageContext messageContext, boolean inclueHeaders) { String retStr = ""; int statusCode = 0; URL neturl; HttpURLConnection connection = null; try { neturl = new URL(url); connection = (HttpURLConnection) neturl.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Accept", "application/json"); connection.setRequestProperty("Accept-Charset", "UTF-8");//ADDED if (auth) { connection.setRequestProperty("Authorization", "Bearer " + getAccessToken(operatorendpoint.getOperator(), messageContext)); //Add JWT token header org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) messageContext) .getAxis2MessageContext(); Object headers = axis2MessageContext .getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS); if (headers != null && headers instanceof Map) { Map headersMap = (Map) headers; String jwtparam = (String) headersMap.get("x-jwt-assertion"); if (jwtparam != null) { connection.setRequestProperty("x-jwt-assertion", jwtparam); } } } if (inclueHeaders) { org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) messageContext) .getAxis2MessageContext(); Object headers = axis2MessageContext .getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS); if (headers != null && headers instanceof Map) { Map headersMap = (Map) headers; Iterator it = headersMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); connection.setRequestProperty((String) entry.getKey(), (String) entry.getValue()); // avoids a ConcurrentModificationException } } } connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); log.debug("Southbound Request URL: " + connection.getRequestMethod() + " " + connection.getURL()); log.debug("Southbound Request Headers: " + connection.getRequestProperties()); log.debug("Southbound Request Body: " + requestStr); //UNICODE BufferedOutputStream wr = new BufferedOutputStream(connection.getOutputStream()); wr.write(requestStr.getBytes("UTF-8")); wr.flush(); wr.close(); statusCode = connection.getResponseCode(); if ((statusCode != 200) && (statusCode != 201) && (statusCode != 400) && (statusCode != 401)) { throw new RuntimeException("Failed : HTTP error code : " + statusCode); } InputStream is = null; if ((statusCode == 200) || (statusCode == 201)) { is = connection.getInputStream(); } else { is = connection.getErrorStream(); } BufferedReader br = new BufferedReader(new InputStreamReader(is)); String output; while ((output = br.readLine()) != null) { retStr += output; } br.close(); log.debug("Southbound Response Status: " + statusCode + " " + connection.getResponseMessage()); log.debug("Southbound Response Headers: " + connection.getHeaderFields()); log.debug("Southbound Response Body: " + retStr); } catch (Exception e) { log.error("[CreditRequestService ], makerequest, " + e.getMessage(), e); return null; } finally { if (connection != null) { connection.disconnect(); } messageContext.setProperty(DataPublisherConstants.RESPONSE_CODE, Integer.toString(statusCode)); messageContext.setProperty(DataPublisherConstants.MSISDN, messageContext.getProperty(MSISDNConstants.USER_MSISDN)); publishWalletPaymentData(statusCode, retStr, messageContext); } return retStr; }
From source file:com.wso2telco.dep.mediator.RequestExecutor.java
/** * * @param url//from w w w . j a v a2 s. co m * @param requestStr * @param messageContext * @return */ public String makeWalletRequest(OperatorEndpoint operatorendpoint, String url, String requestStr, boolean auth, MessageContext messageContext, boolean inclueHeaders) { String retStr = ""; int statusCode = 0; URL neturl; HttpURLConnection connection = null; try { neturl = new URL(url); connection = (HttpURLConnection) neturl.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Accept", "application/json"); connection.setRequestProperty("Accept-Charset", "UTF-8");//ADDED if (auth) { connection.setRequestProperty("Authorization", "Bearer " + getAccessToken(operatorendpoint.getOperator(), messageContext)); //Add JWT token header org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) messageContext) .getAxis2MessageContext(); Object headers = axis2MessageContext .getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS); if (headers != null && headers instanceof Map) { Map headersMap = (Map) headers; String jwtparam = (String) headersMap.get("x-jwt-assertion"); if (jwtparam != null) { connection.setRequestProperty("x-jwt-assertion", jwtparam); } } } if (inclueHeaders) { org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) messageContext) .getAxis2MessageContext(); Object headers = axis2MessageContext .getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS); if (headers != null && headers instanceof Map) { Map headersMap = (Map) headers; Iterator it = headersMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); connection.setRequestProperty((String) entry.getKey(), (String) entry.getValue()); // avoids a ConcurrentModificationException } } } connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); log.info("Southbound Request URL: " + connection.getRequestMethod() + " " + connection.getURL() + " Request ID: " + UID.getRequestID(messageContext)); if (log.isDebugEnabled()) { log.debug("Southbound Request Headers: " + connection.getRequestProperties()); } log.info("Southbound Request Body: " + requestStr + " Request ID: " + UID.getRequestID(messageContext)); //========================UNICODE PATCH========================================= BufferedOutputStream wr = new BufferedOutputStream(connection.getOutputStream()); wr.write(requestStr.getBytes("UTF-8")); wr.flush(); wr.close(); //========================UNICODE PATCH========================================= statusCode = connection.getResponseCode(); if ((statusCode != 200) && (statusCode != 201) && (statusCode != 400) && (statusCode != 401)) { throw new RuntimeException("Failed : HTTP error code : " + statusCode); } InputStream is = null; if ((statusCode == 200) || (statusCode == 201)) { is = connection.getInputStream(); } else { is = connection.getErrorStream(); } BufferedReader br = new BufferedReader(new InputStreamReader(is)); String output; while ((output = br.readLine()) != null) { retStr += output; } br.close(); log.info("Southbound Response Status: " + statusCode + " " + connection.getResponseMessage() + " Request ID: " + UID.getRequestID(messageContext)); if (log.isDebugEnabled()) { log.debug("Southbound Response Headers: " + connection.getHeaderFields()); } log.info("Southbound Response Body: " + retStr + " Request ID: " + UID.getRequestID(messageContext)); } catch (Exception e) { log.error("[WSRequestService ], makerequest, " + e.getMessage(), e); return null; } finally { if (connection != null) { connection.disconnect(); } messageContext.setProperty(DataPublisherConstants.RESPONSE_CODE, Integer.toString(statusCode)); messageContext.setProperty(DataPublisherConstants.MSISDN, messageContext.getProperty(MSISDNConstants.USER_MSISDN)); publishWalletPaymentData(statusCode, retStr, messageContext); } return retStr; }
From source file:edu.ku.brc.util.WebStoreAttachmentMgr.java
/** * @param urlStr/* ww w . j a v a2 s. c om*/ * @param tmpFile * @return * @throws IOException */ private File getFileFromWeb(final String attachLocation, final String mimeType, final Integer scale, final byte[] bytes) { File dlFile = getDLFileForName((scale == null) ? attachLocation : getScaledFileName(attachLocation, scale)); try { dlFile.createNewFile(); dlFile.deleteOnExit(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); return null; } boolean success = false; if (bytes == null) { System.out.println("bytes == null"); } notifyListeners(1); GetMethod getMethod = new GetMethod(readURLStr); // type=<type>&filename=<fname>&coll=<coll>&disp=<disp>&div=<div>&inst=<inst> fillValuesArray(); getMethod.setQueryString(new NameValuePair[] { new NameValuePair("type", (scale != null) ? "T" : "O"), new NameValuePair("scale", "" + scale), new NameValuePair("filename", attachLocation), new NameValuePair("token", generateToken(attachLocation)), new NameValuePair("coll", values[0]), new NameValuePair("disp", values[1]), new NameValuePair("div", values[2]), new NameValuePair("inst", values[3]) }); HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(5000); try { int status = client.executeMethod(getMethod); updateServerTimeDelta(getMethod); if (status == HttpStatus.SC_FORBIDDEN) { System.out.println(getMethod.getResponseBodyAsString()); } if (status == HttpStatus.SC_OK) { InputStream inpStream = getMethod.getResponseBodyAsStream(); if (inpStream != null) { BufferedInputStream in = new BufferedInputStream(inpStream); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(dlFile)); //long totBytes = 0; do { int numBytes = in.read(bytes); if (numBytes == -1) { break; } //totBytes += numBytes; bos.write(bytes, 0, numBytes); } while (true); //log.debug(String.format("Total Bytes for file: %d %d", totBytes, totBytes / 1024)); in.close(); bos.flush(); bos.close(); success = true; } } } catch (HttpException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { getMethod.releaseConnection(); notifyListeners(-1); } if (success) { return dlFile; } else { dlFile.delete(); return null; } }
From source file:hudson.gridmaven.MavenBuilder.java
public void getAndUntar(FileSystem fs, String src, String targetPath) throws FileNotFoundException, IOException { BufferedOutputStream dest = null; InputStream tarArchiveStream = new FSDataInputStream(fs.open(new Path(src))); TarArchiveInputStream tis = new TarArchiveInputStream(new BufferedInputStream(tarArchiveStream)); TarArchiveEntry entry = null;/*from w w w.ja v a 2s . c o m*/ try { while ((entry = tis.getNextTarEntry()) != null) { int count; File outputFile = new File(targetPath, entry.getName()); if (entry.isDirectory()) { // entry is a directory if (!outputFile.exists()) { outputFile.mkdirs(); } } else { // entry is a file byte[] data = new byte[BUFFER_MAX]; FileOutputStream fos = new FileOutputStream(outputFile); dest = new BufferedOutputStream(fos, BUFFER_MAX); while ((count = tis.read(data, 0, BUFFER_MAX)) != -1) { dest.write(data, 0, count); } dest.flush(); dest.close(); } } } catch (Exception e) { e.printStackTrace(); } finally { if (dest != null) { dest.flush(); dest.close(); } tis.close(); } }
From source file:com.topsec.tsm.sim.sysconfig.web.SystemConfigController.java
/** * Agent?// w w w . ja va 2 s .c om * @param request * @param response * @return * @throws Exception */ @RequestMapping(value = "downloadAgentFile") public Object downloadAgentFile(HttpServletRequest request, HttpServletResponse response) throws Exception { String filename = (String) request.getParameter("ftpfilepath"); if (filename.equals("action.rar") || filename.equals("agent.rar")) { response.setHeader("Content-Type", "application/octet-stream"); response.setContentType("text/html;charset=UTF-8"); response.setHeader("Content-Disposition", "attachment; filename=" + filename); CommonUtils.setHeaders4Download(response); String serverHome = System.getProperty("jboss.server.home.dir"); String downPath = (String) FtpConfigUtil.getInstance().getFTPConfigByKey("agent").get("downPath"); if (SystemUtils.IS_OS_WINDOWS) { downPath = StringUtils.replace(downPath, "/", File.separator); } else { downPath = StringUtils.replace(downPath, "\\", File.separator); } String savaLogPathfile = new StringBuilder(serverHome).append(downPath).append(filename).toString(); File file = new File(savaLogPathfile); BufferedInputStream bis = null; BufferedOutputStream bos = null; try { bis = new BufferedInputStream(new FileInputStream(file)); bos = new BufferedOutputStream(response.getOutputStream()); byte[] buff = new byte[2048]; int bytesRead; while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) { bos.write(buff, 0, bytesRead); } bos.flush(); } catch (ClientAbortException e) { //? } catch (Exception e) { log.error("...."); log.error(e.getMessage()); } finally { ObjectUtils.close(bis); ObjectUtils.close(bos); } } return null; }
From source file:com.stfalcon.contentmanager.ContentManager.java
protected String getFileFromContentProvider(String uri) { BufferedInputStream inputStream = null; BufferedOutputStream outStream = null; ParcelFileDescriptor parcelFileDescriptor = null; try {// w w w.ja v a 2 s. co m String localFilePath = generateFileName(uri); parcelFileDescriptor = activity.getContentResolver().openFileDescriptor(Uri.parse(uri), "r"); FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor(); inputStream = new BufferedInputStream(new FileInputStream(fileDescriptor)); BufferedInputStream reader = new BufferedInputStream(inputStream); outStream = new BufferedOutputStream(new FileOutputStream(localFilePath)); byte[] buf = new byte[2048]; int len; while ((len = reader.read(buf)) > 0) { outStream.write(buf, 0, len); } outStream.flush(); uri = localFilePath; } catch (IOException e) { return uri; } finally { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { try { parcelFileDescriptor.close(); } catch (IOException e) { e.printStackTrace(); } } try { outStream.flush(); outStream.close(); inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } return uri; }
From source file:com.wso2telco.dep.mediator.RequestExecutor.java
/** * Make request.//from ww w. ja va 2 s.c o m * * @param operatorendpoint * the operatorendpoint * @param url * the url * @param requestStr * the request str * @param auth * the auth * @param messageContext * the message context * @return the string */ public String makeRequest(OperatorEndpoint operatorendpoint, String url, String requestStr, boolean auth, MessageContext messageContext, boolean inclueHeaders) { //MO Callback boolean isMoCallBack = false; JSONObject jsonObject = null; try { jsonObject = new JSONObject(requestStr); } catch (JSONException error) { error.printStackTrace(); } Iterator<String> keys = jsonObject.keys(); if (keys.hasNext()) { String key = (String) keys.next(); if (key.equals("inboundSMSMessageNotification") || key.equals("deliveryInfoNotification")) { isMoCallBack = true; } } try {// check for charge operation. if true append ESB url JSONObject jsonObj = new JSONObject(requestStr); String transactionOperationStatus = jsonObj.getJSONObject("amountTransaction") .getString("transactionOperationStatus"); String status = "Charged"; if (status.equals(transactionOperationStatus)) { url = modifyEndpoint(url, operatorendpoint.getOperator(), messageContext); } } catch (JSONException ignore) { } ICallresponse icallresponse = null; String retStr = ""; int statusCode = 0; URL neturl; HttpURLConnection connection = null; try { // String Authtoken = AccessToken; // //FileUtil.getApplicationProperty("wow.api.bearer.token"); // String encodeurl = URLEncoder.encode(url, "UTF-8"); neturl = new URL(url); connection = (HttpURLConnection) neturl.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Accept", "application/json"); //connection.setRequestProperty("charset", "utf-8"); if (auth) { connection.setRequestProperty("Authorization", "Bearer " + getAccessToken(operatorendpoint.getOperator(), messageContext)); // Add JWT token header org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) messageContext) .getAxis2MessageContext(); Object headers = axis2MessageContext .getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS); if (headers != null && headers instanceof Map) { Map headersMap = (Map) headers; String jwtparam = (String) headersMap.get("x-jwt-assertion"); if (jwtparam != null) { connection.setRequestProperty("x-jwt-assertion", jwtparam); } } } if (inclueHeaders) { org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) messageContext) .getAxis2MessageContext(); Object headers = axis2MessageContext .getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS); if (headers != null && headers instanceof Map) { Map headersMap = (Map) headers; Iterator it = headersMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); connection.setRequestProperty((String) entry.getKey(), (String) entry.getValue()); // avoids a // ConcurrentModificationException } } } connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); log.info("Southbound Request URL: " + connection.getRequestMethod() + " " + connection.getURL() + " Request ID: " + UID.getRequestID(messageContext)); if (log.isDebugEnabled()) { log.debug("Southbound Request Headers: " + connection.getRequestProperties()); } log.info("Southbound Request Body: " + requestStr + " Request ID: " + UID.getRequestID(messageContext)); //========================UNICODE PATCH========================================= BufferedOutputStream wr = new BufferedOutputStream(connection.getOutputStream()); wr.write(requestStr.getBytes("UTF-8")); wr.flush(); wr.close(); //========================UNICODE PATCH========================================= /*DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(requestStr); wr.flush(); wr.close();*/ statusCode = connection.getResponseCode(); if ((statusCode != 200) && (statusCode != 201) && (statusCode != 400) && (statusCode != 401)) { throw new RuntimeException("Failed : HTTP error code : " + statusCode); } InputStream is = null; if ((statusCode == 200) || (statusCode == 201)) { is = connection.getInputStream(); } else { is = connection.getErrorStream(); } BufferedReader br = new BufferedReader(new InputStreamReader(is)); String output; while ((output = br.readLine()) != null) { retStr += output; } br.close(); log.info("Southbound Response Status: " + statusCode + " " + connection.getResponseMessage() + " Request ID: " + UID.getRequestID(messageContext)); if (log.isDebugEnabled()) { log.debug("Southbound Response Headers: " + connection.getHeaderFields()); } log.info("Southbound Response Body: " + retStr + " Request ID: " + UID.getRequestID(messageContext)); } catch (Exception e) { log.error("[WSRequestService ], makerequest, " + e.getMessage(), e); return null; } finally { if (connection != null) { connection.disconnect(); } log.debug( "Mo OR DN CallBack : " + isMoCallBack + " requestStr : " + requestStr + " retStr : " + retStr); messageContext.setProperty(DataPublisherConstants.RESPONSE_CODE, Integer.toString(statusCode)); messageContext.setProperty(DataPublisherConstants.MSISDN, messageContext.getProperty(MSISDNConstants.USER_MSISDN)); /* TODO:This need to consider when publishing request data if (isMoCallBack) { publishResponseData(statusCode, requestStr, messageContext); }else { publishResponseData(statusCode, retStr, messageContext); }*/ } return retStr; }
From source file:com.wooki.services.parsers.DocumentToXHTML.java
public InputStream performTransformation(Resource xmlDocument) { BufferedInputStream in;/*from ww w .jav a2 s . c o m*/ BufferedOutputStream out; ByteArrayOutputStream result; Tidy tidy = new Tidy(); java.util.Properties props = new java.util.Properties(); props.setProperty("new-inline-tags", "page-break,page-number,page-numbers,wooki,xsl:value-of,xsl:for-each,quote"); props.setProperty("new-blocklevel-tags", "for,page-header,page-footer,xsl:value-of,xsl:for-each"); props.setProperty("new-empty-tags", "page-break,page-number,page-numbers,xsl:value-of"); // props.setProperty("new-pre-tags", "for,header,footer"); props.setProperty("new-pre-tags", "wooki"); tidy.setConfigurationFromProps(props); // tidy.setDocType("omit"); tidy.setXmlOut(xmlOut); tidy.setXHTML(true); tidy.setEmacs(true); tidy.setErrfile("tidyErrors.txt"); tidy.setFixBackslash(true); tidy.setNumEntities(true); tidy.setQuoteNbsp(false); tidy.setCharEncoding(Configuration.LATIN1); // tidy.setInputEncoding("ISO-8859-2"); tidy.setFixComments(true); tidy.setQuoteAmpersand(false); tidy.setEncloseText(true); tidy.setEncloseBlockText(true); // tidy.setWord2000(true); try { tidy.setErrout(new PrintWriter(new FileWriter("tidyErrors.txt"), true)); in = new BufferedInputStream(xmlDocument.getInputStream()); out = new BufferedOutputStream(result = new ByteArrayOutputStream()); byte[] XMLHeader = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n".getBytes(); out.write(XMLHeader, 0, XMLHeader.length); tidy.parse(in, out); out.flush(); return new ByteArrayInputStream(result.toByteArray()); } catch (IOException ioe) { ioe.printStackTrace(); logger.error(ioe.getLocalizedMessage()); return null; } }
From source file:org.zilverline.service.CollectionManagerImpl.java
/** * unZips a given zip file into cache directory with derived name. e.g. c:\temp\file.zip wil be unziiped into * [cacheDir]\file_zip\./* w w w . j a va 2 s . co m*/ * * @param sourceZipFile the ZIP file to be unzipped * @param thisCollection the collection whose cache and contenDir is used * * @return File (new) directory containing zip file */ public static File unZip(final File sourceZipFile, final FileSystemCollection thisCollection) { // specify buffer size for extraction final int aBUFFER = 2048; File unzipDestinationDirectory = null; ZipFile zipFile = null; FileOutputStream fos = null; BufferedOutputStream dest = null; BufferedInputStream bis = null; try { // Specify destination where file will be unzipped unzipDestinationDirectory = file2CacheDir(sourceZipFile, thisCollection); log.info("unzipping " + sourceZipFile + " into " + unzipDestinationDirectory); // Open Zip file for reading zipFile = new ZipFile(sourceZipFile, ZipFile.OPEN_READ); // Create an enumeration of the entries in the zip file Enumeration zipFileEntries = zipFile.entries(); while (zipFileEntries.hasMoreElements()) { // grab a zip file entry ZipEntry entry = (ZipEntry) zipFileEntries.nextElement(); String currentEntry = entry.getName(); log.debug("Extracting: " + entry); File destFile = new File(unzipDestinationDirectory, currentEntry); // grab file's parent directory structure File destinationParent = destFile.getParentFile(); // create the parent directory structure if needed destinationParent.mkdirs(); // extract file if not a directory if (!entry.isDirectory()) { bis = new BufferedInputStream(zipFile.getInputStream(entry)); int currentByte; // establish buffer for writing file byte[] data = new byte[aBUFFER]; // write the current file to disk fos = new FileOutputStream(destFile); dest = new BufferedOutputStream(fos, aBUFFER); // read and write until last byte is encountered while ((currentByte = bis.read(data, 0, aBUFFER)) != -1) { dest.write(data, 0, currentByte); } dest.flush(); dest.close(); bis.close(); } } zipFile.close(); // delete the zip file if it is in the cache, we don't need to store // it, since we've extracted the contents if (FileUtils.isIn(sourceZipFile, thisCollection.getCacheDirWithManagerDefaults())) { sourceZipFile.delete(); } } catch (Exception e) { log.error("Can't unzip: " + sourceZipFile, e); } finally { try { if (fos != null) { fos.close(); } if (dest != null) { dest.close(); } if (bis != null) { bis.close(); } } catch (IOException e1) { log.error("Error closing files", e1); } } return unzipDestinationDirectory; }
From source file:com.mobile.natal.natalchart.NetworkUtilities.java
/** * Send a file via HTTP POST with basic authentication. * * @param context the context to use./*from ww w. ja va2 s .c o m*/ * @param urlStr the server url to POST to. * @param file the file to send. * @param user the user or <code>null</code>. * @param password the password or <code>null</code>. * @return the return string from the POST. * @throws Exception if something goes wrong. */ public static String sendFilePost(Context context, String urlStr, File file, String user, String password) throws Exception { BufferedOutputStream wr = null; FileInputStream fis = null; HttpURLConnection conn = null; try { fis = new FileInputStream(file); long fileSize = file.length(); // Authenticator.setDefault(new Authenticator(){ // protected PasswordAuthentication getPasswordAuthentication() { // return new PasswordAuthentication("test", "test".toCharArray()); // } // }); urlStr = urlStr + "?name=" + file.getName(); conn = makeNewConnection(urlStr); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true); // conn.setChunkedStreamingMode(0); conn.setUseCaches(true); // conn.setRequestProperty("Accept-Encoding", "gzip "); // conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Type", "application/octet-stream"); // conn.setRequestProperty("Content-Length", "" + fileSize); // conn.setRequestProperty("Connection", "Keep-Alive"); if (user != null && password != null && user.trim().length() > 0 && password.trim().length() > 0) { conn.setRequestProperty("Authorization", getB64Auth(user, password)); } conn.connect(); wr = new BufferedOutputStream(conn.getOutputStream()); long bufferSize = Math.min(fileSize, maxBufferSize); if (GPLog.LOG) GPLog.addLogEntry(TAG, "BUFFER USED: " + bufferSize); byte[] buffer = new byte[(int) bufferSize]; int bytesRead = fis.read(buffer, 0, (int) bufferSize); long totalBytesWritten = 0; while (bytesRead > 0) { wr.write(buffer, 0, (int) bufferSize); totalBytesWritten = totalBytesWritten + bufferSize; if (totalBytesWritten >= fileSize) break; bufferSize = Math.min(fileSize - totalBytesWritten, maxBufferSize); bytesRead = fis.read(buffer, 0, (int) bufferSize); } wr.flush(); int responseCode = conn.getResponseCode(); return getMessageForCode(context, responseCode, context.getResources().getString(R.string.file_upload_completed_properly)); } catch (Exception e) { throw e; } finally { if (wr != null) wr.close(); if (fis != null) fis.close(); if (conn != null) conn.disconnect(); } }