I want to try download a file from resume in android studio, i have try my code with open stream and don't have any problem but in this code:
public void startStream2(Context context) {
try {
URL url = new URL(file.getFileUrl());
StrictMode.ThreadPolicy ploicy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(ploicy);
URLConnection connection = url.openConnection();
int downloaded = 0;
BufferedOutputStream bout;
f = new File(downloadPath, file.getName());
if (f.exists()) {
downloaded = (int) f.length();
connection.setRequestProperty("Range", "bytes=" + (f.length()) + "-");
}
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestProperty("User-Agent","Mozilla/5.0 ( compatible ) ");
connection.setRequestProperty("Accept","*/*");
connection.connect();
int response=((HttpURLConnection)connection).getResponseCode();
Log.e(TAG, "startStream2: "+ response );
if (response>399 && response<601){
InputStreamReader sr;
sr = new InputStreamReader(((HttpURLConnection) connection).getErrorStream(), "UTF-8");
StringBuilder builder = new StringBuilder();
for (int bt = 0; (bt = sr.read()) != -1;) {
builder.append((char)bt);
}
sr.close();
Log.e(TAG, "startStream2: "+builder.toString());
}
InputStream inp=connection.getInputStream();
BufferedInputStream in = new BufferedInputStream(inp);
stream2 = (downloaded == 0) ? new FileOutputStream(f) : new FileOutputStream(f, true);
bout = new BufferedOutputStream(stream2, 1024);
byte[] data = new byte[1024];
int x = 0;
while ((x = in.read(data, 0, 1024)) >= 0) {
bout.write(data, 0, x);
downloaded += x;
int percent = ((int) downloaded * 100) / (int) Size;
//set percent progress
}
}catch (Exception e){
Log.e(TAG, "startStream2: ",e );
}
}
Error log:
startStream2: 405 startStream2:
405 Not Allowed
405 Not Allowed
nginx
startStream2:
java.io.FileNotFoundException:
at
com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:242)
I have test the url before and don't have any problem with download from first or resume.
How can i resolve it?
thanks.
connection.setDoOutput(true);
The problem is here. It changes the HTTP verb from GET to POST. You don't want to POST. You aren't sending any output. Remove it.
And if the response code isn't 200 you should not get the input stream, otherwise it will throw an exception. You can get the error stream if you want more info, but there isn't an input stream at this point.
You can also remove
connection.connect();
and
connection.setDoInput(true);
They don't do anything that doesn't already happen.
remove these lines
connection.setDoInput(true);
connection.setDoOutput(true);
Finally i have resolved it by this code:
public void startStream2(Context context) {
try {
URL url = new URL(file.getFileUrl());
StrictMode.ThreadPolicy ploicy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(ploicy);
URLConnection connection = url.openConnection();
int downloaded = 0;
BufferedOutputStream bout;
f = new File(downloadPath, file.getName());
if (f.exists()) {
downloaded = (int) f.length();
connection.setRequestProperty("Range", "bytes=" + (f.length()) + "-");
}
connection.setDoInput(true);
connection.setRequestProperty("User-Agent","Mozilla/5.0 ( compatible ) ");
connection.setRequestProperty("Accept","*/*");
int response=((HttpURLConnection)connection).getResponseCode();
Log.e(TAG, "startStream2: "+ response );
if (response>399 && response<601){
InputStreamReader sr;
sr = new InputStreamReader(((HttpURLConnection) connection).getErrorStream(), "UTF-8");
StringBuilder builder = new StringBuilder();
for (int bt = 0; (bt = sr.read()) != -1;) {
builder.append((char)bt);
}
sr.close();
Log.e(TAG, "startStream2: "+builder.toString());
}
InputStream inp=connection.getInputStream();
BufferedInputStream in = new BufferedInputStream(inp);
stream2 = (downloaded == 0) ? new FileOutputStream(f) : new FileOutputStream(f, true);
bout = new BufferedOutputStream(stream2, 1024);
byte[] data = new byte[1024];
int x = 0;
while ((x = in.read(data, 0, 1024)) >= 0) {
bout.write(data, 0, x);
downloaded += x;
int percent = ((int) downloaded * 100) / (int) Size;
//set percent progress
}
}catch (Exception e){
Log.e(TAG, "startStream2: ",e );
}
}
Thank a lot!
Related
When I am downloading a file from the server if suppose I killed or destroy the application means it will download only half of data how to resume download when application open or how to delete incomplete data in the file.
Any ideas?
private void downloadBookDetails(String pMainFolder, String pFileName, String pDownloadURL) {
Log.i(TAG, "Coming to this downloadBookDetails ");
try {
URL url = new URL(pDownloadURL);
URLConnection ucon = url.openConnection();
ucon.setReadTimeout(5000);
ucon.setConnectTimeout(10000);
InputStream is = ucon.getInputStream();
BufferedInputStream inStream = new BufferedInputStream(is, 1024 * 5);
File directory = new File(pMainFolder, pFileName);
FileOutputStream outStream = new FileOutputStream(directory);
byte[] buff = new byte[5 * 1024];
int len;
while ((len = inStream.read(buff)) != -1) {
outStream.write(buff, 0, len);
}
outStream.flush();
outStream.close();
inStream.close();
} catch (Exception e) {
//Add Network Error.
Log.e(TAG, "Download Error Exception " + e.getMessage());
e.printStackTrace();
}
}
You should use DownLoad Manager for downloads in your app. This will automatically handles all the things for you. Which is a system service that can handle long-running HTTP downloads.
UPDATE
If you want to download the file by your own then you can use it like below:
#SuppressLint("Wakelock")
#Override
protected String doInBackground(String... sUrl) {
// take CPU lock to prevent CPU from going off if the user
// presses the power button during download
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
getClass().getName());
wl.acquire();
try {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
File SDCardRoot = Environment.getExternalStorageDirectory();
File file = new File(SDCardRoot,"/"+fileName);
int downloaded=0;
if(file.exists()){
downloaded=(int) file.length();
connection.setRequestProperty("Range", "bytes=" + (int) file.length() + "-");
}
else{
file.createNewFile();
}
connection.setDoInput(true);
connection.setDoOutput(true);
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
// this will be useful to display download percentage
// might be -1: server did not report the length
int fileLength = connection.getContentLength()+(int)file.length();
// download the file
input = connection.getInputStream();
if(downloaded>0){
output = new FileOutputStream(file,true);
}
else{
output = new FileOutputStream(file);
}
byte data[] = new byte[1024];
long total = downloaded;
int count;
mProgressDialog.setMax(fileLength/1024);
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled())
return null;
total += count;
// publishing the progress....
if (fileLength > 0) // only if total length is known
publishProgress((int)total/1024);
output.write(data, 0, count);
}
output.flush();
if (output != null)
output.close();
if (input != null)
input.close();
if (connection != null)
connection.disconnect();
wl.release();
return null;
} catch (Exception e) {
return e.toString();
}
}
catch (Exception e) {
return e.toString();
}
}
The problem I am having is that I can only upload images from the projects directory (/home/usr/workspace/project/~from here~).
For obvious reasons this won't work when I go to publish this feature. I am not sure where I should configure this differently. Help me stack overflow you're my only hope.
#RequestMapping("/saveImage")
public String getPreparedUploadUrl(#RequestParam File fileName,
HttpSession session) throws IOException, InterruptedException {
java.util.Date expiration = new java.util.Date();
long msec = expiration.getTime();
msec += 1000 * 60 * 60; // Add 1 hour.
expiration.setTime(msec);
ObjectMetadata md = new ObjectMetadata();
md.setContentType("image/jpg");
md.setContentLength(fileName.length());
md.setHeader(fileName.getName(), fileName.getAbsolutePath());
File file = new File(fileName.getAbsolutePath());
FileInputStream fis = new FileInputStream(file);
byte[] content_bytes = IOUtils.toByteArray(fis);
String md5 = new
String(Base64.encodeBase64(DigestUtils.md5(content_bytes)));
md.setContentMD5(md5);
GeneratePresignedUrlRequest generatePresignedUrlRequest =
new GeneratePresignedUrlRequest("wandering-wonderland-
images", fileName.getName());
generatePresignedUrlRequest.setMethod(HttpMethod.PUT);
generatePresignedUrlRequest.setExpiration(expiration);
URL s =
s3client.generatePresignedUrl(generatePresignedUrlRequest);
try {
UploadObject(s, fileName);
} catch (IOException e) {
e.printStackTrace();
}
session.setAttribute("saved", fileName + " has been saved!");
return "redirect:/saved3";
}
// working, don't f#$# with it!
public static void UploadObject(URL url, File file) throws
IOException, InterruptedException {
HttpURLConnection connection=(HttpURLConnection)
url.openConnection();
InputStream inputStream = new
FileInputStream(file.getAbsolutePath());
connection.setDoOutput(true);
connection.setRequestMethod("PUT");
OutputStream out =
connection.getOutputStream();
byte[] buf = new byte[1024];
int count;
int total = 0;
long fileSize = file.length();
while ((count =inputStream.read(buf)) != -1)
{
if (Thread.interrupted())
{
throw new InterruptedException();
}
out.write(buf, 0, count);
total += count;
int pctComplete = new Double(new Double(total) / new
Double(fileSize) * 100).intValue();
System.out.print("\r");
System.out.print(String.format("PCT Complete: %d",
pctComplete));
}
System.out.println();
out.close();
inputStream.close();
int responseCode = connection.getResponseCode();
System.out.println("Service returned response code " +
responseCode);
}
I am downloading a PDF from a URL and saving it to my local drive.
The download code is working perfectly, the problem is that when I try to measure the size of the file it always claims it to be 52 bytes. I'm baffled... could you please review my code and tell me if I'am missing something?
try {
link = new URL("http://www.annualreports.co.uk/HostedData/AnnualReports/PDF/LSE_" + entry[0] + "_2015.pdf");
// http://www.annualreports.co.uk/HostedData/AnnualReports/PDF/LSE_BT_2015.pdf
InputStream in = new BufferedInputStream(link.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n = 0;
while (-1!=(n=in.read(buf)))
{
out.write(buf, 0, n);
}
out.close();
in.close();
byte[] response = out.toByteArray();
FileOutputStream fos = new FileOutputStream(fileName);
fos.write(response);
fos.close();
} catch (Exception e) {
System.out.println("Couldn't retrieve : " + entry[1] + " " + year);
}
int bytes = fileName.length();
System.out.println(bytes);
Here. Just simply try this.
URL url = new URL("http://www.annualreports.co.uk/HostedData/AnnualReports/PDF/LSE_" + entry[0] + "_2015.pdf");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.addRequestProperty("User-Agent", "Mozilla/4.76");
int size = conn.getContentLength();
if (size < 0) {
System.out.println("File not found");
} else {
System.out.println("File size in Bytes: " + size);
}
We have to connect to a asp.net server to download media items.
We've got this code:
URLConnection urlConnection;
try {
String localTempPath = SettingsManager.getInstance().getLocalTempMediaItemFilePath(loadingItem);
URL serverPath = new URL(SettingsManager.getInstance().getServerMediaItemFilePath(loadingItem));
urlConnection = serverPath.openConnection();
String urlParameters = "http://tempuri.org/";
HttpURLConnection connection = (HttpURLConnection) serverPath.openConnection();
connection.setFollowRedirects(true);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
for (String cookie:cookies.keySet()) {
connection.setRequestProperty("Cookie", cookie + "=" + cookies.get(cookie));
} //only one Cookie: ASPNET_SessionId=...
connection.connect();
int response = connection.getResponseCode();
File f = new File (localTempPath);
f.createNewFile();
if (f.exists()){
FileOutputStream fileOutput = new FileOutputStream(f);
//Get Response
InputStream is = connection.getInputStream();
int totalsize = connection.getContentLength();
int downloadedSize = 0;
byte[] buffer = new byte [1024];
int bufferLength = 0;
while ((bufferLength = is.read(buffer)) > 0){
fileOutput.write(buffer,0,bufferLength);
downloadedSize += bufferLength;
}
fileOutput.close();
}
return null;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
}
We have to send the Session-Cookie to the server but we always get a 404:java.io.FileNotFoundException: http://possuite.emmgt.at/v30/dataservice/MediaItem/6629.mi
I want to upload an image to FTP Server. Currently i am using JDeveloper 12c(12.1.3.0).
My Code:
private static final int BUFFER_SIZE = 4096;
public String fileUploadMethod(String imagePath){
String ftpUrl = "ftp://";
String host = "http://192.168.0.42";
String user = "XXXXXX";
String pass = "XXXXXX";
String filePath = "783771-1.jpg";
String uploadPath = imagePath;
ftpUrl =ftpUrl + user +":"+ pass+"#"+host+"/"+filePath+";";
System.out.println("Upload URL: " + ftpUrl);
try {
URL url = new URL(ftpUrl);
URLConnection conn = url.openConnection();
OutputStream outputStream = conn.getOutputStream();
FileInputStream inputStream = new FileInputStream(uploadPath);
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
inputStream.close();
outputStream.close();
System.out.println("File uploaded");
return "File uploaded";
} catch (IOException ex) {
ex.printStackTrace();
}
return null;
}
I am getting an error MalFormedURLException i.e. in detail message "unknown protocol:ftp"
Is there any other option to upload an image using JDeveloper.
Any idea regarding this.
Thanks, Siddharth
Your ftpUrl is wrong. Remove http:// in the host variable. Should be ok then
I haven't really tried ftp upload. But I had tried with multipart form upload. As far as I know, MAF doesnt provide Out-Of-Box support for file upload. What I did was essential recreating the HTTP stream for the image upload.
The POC code is attached below. This may be definitely the CRUDEST implementation but I am not sure if there is a better way.
public void doUpload() {
try {
DeviceManager dm = DeviceManagerFactory.getDeviceManager();
String imgData =
dm.getPicture(50, DeviceManager.CAMERA_DESTINATIONTYPE_FILE_URI, DeviceManager.CAMERA_SOURCETYPE_CAMERA,
false, DeviceManager.CAMERA_ENCODINGTYPE_PNG, 0, 0);
imgData = imgData.substring(7, imgData.length());
int start = imgData.lastIndexOf('/');
String fileName = imgData.substring(start+1, imgData.length());
RestServiceAdapter restServiceAdapter = Model.createRestServiceAdapter();
restServiceAdapter.clearRequestProperties();
String requestMethod = RestServiceAdapter.REQUEST_TYPE_POST;
String requestEndPoint = restServiceAdapter.getConnectionEndPoint("serverBaseUrl");
String requestURI = "/workers/100000018080264";
String request = requestEndPoint + requestURI;
HashMap httpHeadersValue = new HashMap();
httpHeadersValue.put("X-ANTICSRF", "TRUE");
httpHeadersValue.put("Connection", "Keep-Alive");
httpHeadersValue.put("content-type","multipart/form-data; boundary=----------------------------4abf1aa47e18");
// Get the connection
HttpConnection connection = restServiceAdapter.getHttpConnection(requestMethod, request, httpHeadersValue);
OutputStream os = connection.openOutputStream();
byte byteBuffer[] = new byte[50];
int len;
//String temp is appended before the image body
String temp = "------------------------------4abf1aa47e18\r\nContent-Disposition: form-data; name=\"file\"; filename=\"" +fileName+ "\"\r\nContent-Type: image/jpeg\r\n\r\n";
InputStream stream = new ByteArrayInputStream(temp.getBytes("UTF-8"));
if (stream != null) {
while ((len = stream.read(byteBuffer)) >= 0) {
os.write(byteBuffer, 0, len);
}
stream.close();
}
FileInputStream in = new FileInputStream(imgData);
if (in != null) {
while ((len = in.read(byteBuffer)) >= 0) {
os.write(byteBuffer, 0, len);
}
in.close();
}
//The below String is appended after the image body
InputStream stream2 =new ByteArrayInputStream("\r\n------------------------------4abf1aa47e18--\r\n".getBytes("UTF-8"));
if (stream2 != null) {
while ((len = stream2.read(byteBuffer)) >= 0) {
os.write(byteBuffer, 0, len);
}
stream2.close();
}
int status = connection.getResponseCode();
InputStream inputStream = restServiceAdapter.getInputStream(connection);
ByteArrayOutputStream incomingBytes = new ByteArrayOutputStream() // get and process the response.
while ((len = inputStream.read(byteBuffer)) >= 0) {
incomingBytes.write(byteBuffer, 0, len);
}
String ret = incomingBytes.toString();
incomingBytes.close();
} catch (Exception e) {
e.printStackTrace();
}
}