Saving BufferedHttpEntity to File - android

How do you save an entity to SDCard, in a streamed manner (To avoid memory issues).
I cant find any solid documentation on the matter.
response = httpClient.execute(request);
BufferedHttpEntity responseEntity = new BufferedHttpEntity(response.getEntity());
FileOutputStream fos = new FileOutputStream(Files.SDCARD + savePath);
responseEntity.writeTo(fos);
fos.flush();
fos.close();
This gives me the file, but with no contents. (2KB in size). So its not writing properly.
The server is sending a FileStream. Which I have confirmed to work.

I would try this approach:
HttpResponse response = httpClient.execute(post);
InputStream input = response.getEntity().getContent();
OutputStream output = new FileOutputStream("path/to/file");
int read = 0;
byte[] bytes = new byte[1024];
while ((read = input.read(bytes)) != -1) {
output.write(bytes, 0, read);
}
output.close();
Hope it helps.
Cheers.

Related

Android socket client get reply from server

I'm new in socket. I really need your help.
I have create a socket client in android, and send the server a picture successfully. The next task what I want to do is receiving a JSON file from the server as the reply. However, after I close the outstream, it always tell me, " Socket is closed".
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
//write out the stream
out.close();
InputStream inputStream = socket.getInputStream();
//!!it always throws SocketException, and tell me socket is closed
byte buffer[] = new byte[1024 * 4];
int temp = 0;
// read data from inputStream
while ((temp = inputStream.read(buffer)) != -1) {
System.out.println(new String(buffer, 0, temp));
}
I have tried many ways to solve it.
1.close the outstream lately
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
//write out the stream
InputStream inputStream = socket.getInputStream();
byte buffer[] = new byte[1024 * 4];
int temp = 0;
//!!My client seems to wait for some messages from server.
//However, since I didn't close the outputStream, the server can't stop writing the file from my outputStream.
//As a result, the server can't send back JSON file to me as a reply.
//My server and client all go blocked.
while ((temp = inputStream.read(buffer)) != -1) {
System.out.println(new String(buffer, 0, temp));
}
out.close();
2.connect the socket again
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
//write out the stream
out.close();
socket.connect(sc_add,2000);
//!!it will tell me the socket is already connected this time
InputStream inputStream = socket.getInputStream();
//it always throws SocketException, and tell me socket is closed
byte buffer[] = new byte[1024 * 4];
int temp = 0;
// read data from inputStream
while ((temp = inputStream.read(buffer)) != -1) {
System.out.println(new String(buffer, 0, temp));
}
Thank you for your help.

Reading InputStream after writing

I am trying to read InputStream after writing output stream to sdcard. I have downloaded file from HttpURLConnection. File is successfuly written to sdcard. But I am trying to read inputstream from same file but contents are not being read properly. On emulator some contents are shown but on actual device contents are not shown. Can you please help what can be the issue? I am posting downloading, writing and reading code.
fileUrl = new URL(filename);
HttpURLConnection connection = (HttpURLConnection)fileUrl.openConnection();
InputStream is = connection.getInputStream();
/**
* Create file with input stream
*/
File downloadFile = new File("/sdcard/", "myFile3.pdf");
downloadFile.createNewFile();
final FileOutputStream outputStream = new FileOutputStream(downloadFile);
int availbleLength = is.available();
byte[] bytes = new byte[availbleLength];
int len1 = 0;
while ((len1 = is.read(bytes)) > 0) {
outputStream.write(bytes, 0, len1);
}
outputStream.flush();
outputStream.close();
File myFile = new File("/sdcard/myFile3.pdf");
InputStream inputStream = new FileInputStream(myFile);
byte[] buffer = new byte[inputStream.available()];
inputStream.read(buffer);
System.out.println("Byte Lenght: " + buffer.length);
inputStream.available() is only an estimate not actual length of the complete input data.
FileInputStream.available()

FileNotFoundException with HttpURLConnection in Android

URL url = new URL(path);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
String PATH = "/mnt/sdcard/Android/";
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, "version.txt");
if(outputFile.exists()){
outputFile.delete();
}
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
Exception caught: java.io.FileNotFoundException http://192.168.2.143/version.txt, where path="http://192.168.2.143/version.txt", I use browser in my device to open http://192.168.2.143/version.txt, can be opened. I have INTERNET permission in my manifest. Any idea?
It's the same problem I was having:
HttpUrlConnection returns FileNotFoundException if you try to read the getInputStream() from the connection.
You should instead use getErrorStream() when the status code is higher than 400.
More than this, please be careful since it's not only 200 to be the success status code, even 201, 204, etc. are often used as success statuses.
Here is an example of how I went to manage it
... connection code code code ...
// Get the response code
int statusCode = connection.getResponseCode();
InputStream is = null;
if (statusCode >= 200 && statusCode < 400) {
// Create an InputStream in order to extract the response object
is = connection.getInputStream();
}
else {
is = connection.getErrorStream();
}
... callback/response to your handler....
In this way, you'll be able to get the needed response in both success and error cases.
Hope this helps!
Try this to read file over the internet: Reading Text File From Server on Android
I'm not sure you can use File.

file saving on android

I am making a xml file and saving it on my device code follows
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://xx:xx:xx:xx:yy/LoginAndroid.asmx/login");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String responseBody = EntityUtils.toString(response.getEntity());
//Toast.makeText( getApplicationContext(),"responseBody: "+responseBody,Toast.LENGTH_SHORT).show();
//saving the file as a xml
FileOutputStream fOut = openFileOutput("loginData.xml",MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write(responseBody);
osw.flush();
osw.close();
//reading the file as xml
FileInputStream fIn = openFileInput("loginData.xml");
InputStreamReader isr = new InputStreamReader(fIn);
char[] inputBuffer = new char[responseBody.length()];
isr.read(inputBuffer);
String readString = new String(inputBuffer);
FIle is saving I can also read the file every thing is ok but look at this line
char[] inputBuffer = new char[responseBody.length()];
it is calculating string length which is saved at the time of Saving the file.I am saving the file in one Acivity and reading it from another activity and my application will save the file locally once so I could not be able to get the length of that return string every time So is there any way to allocate the size of char[] inputBuffer dynamically?
you can use the below code in your another activity to read the file. Have a look at BufferedReader class.
InputStream instream = new FileInputStream("loginData.xml");
// if file the available for reading
if (instream != null) {
// prepare the file for reading
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
// read every line of the file into the line-variable, on line at the time
while (buffreader.hasNext()) {
line = buffreader.readLine();
// do something with the line
}
}
Edit:
The above code is working fine for reading a file, but if you just want to allocate the size of char[] inputBuffer dynamicall then you can use the below code.
InputStream is = mContext.openFileInput("loginData.xml");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
while ((int bytesRead = is.read(b)) != -1) {
bos.write(b, 0, bytesRead);
}
byte[] inputBuffer = bos.toByteArray();
Now , make use inputBuffer as you want.

the download image be corrupted at android app

simply i need to download an image but the problem is the image get corrupted !!!
i find many way to download the image but still this problem appeared .
i try do this :
File path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File file2 = new File(path,"DemoPictureX.png");
InputStream is=(InputStream) new URL("http://androidsaveitem.appspot.com/downloadjpg").getContent();
OutputStream os = new FileOutputStream(file2);
byte[] data = new byte[is.available()];
is.read(data);
os.write(data);
is.close();
os.close();
i think it read just read some row from the image !!!
you need a loop and read with a smaller buffer (like 1024 bytes) from the stream.
URL url = new URL("your url here");
URLConnection connection = url.openConnection();
InputStream is = connection.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
FileOutputStream fos = new FileOutputStream(targetFile);
byte buffer[] = new byte[1024];
int read;
while ((read = bis.read(buffer)) > 0) {
fos.write(buffer, 0, read);
}
fos.flush();
fos.close();
bis.close();
is.close();
This should work for you

Categories

Resources