download json file and store locally on my android device - java

I am doing a rest call and getting a json file from the server by this
HttpGet httpget = new HttpGet("someurl");
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
InputStream source = entity.getContent();
now i want to store this into a local file I am using FileOutputStream to do this but the problem is how to effectively convert the inputstream to outputstream if i am using something like this
FileOutputStream fos = openFileOutput(filename,Context.MODE_PRIVATE);
int nextChar;
while ((nextChar = source.read()) != -1) {
fos.write((char) nextChar);
System.out.println((char) nextChar);
fos.flush();
}
it is storing very slow the file which i am getting is upto 100kb is there any other faster method or any other way which i can use to store the json file in my device?
My applications uses this json heavily and i don't want to call the REST each time.
thanks
Pranay

try to use org.apache.commons.io.IOUtils's
IOUtils.copy(is,fos);
lets see, what happening. Thanks,
EDIT: Why not you are use sqlite database? parse JSON result onetime and insert it in database only onetime stuff then always you get fast execution.
EDIT: try android's internal storage for write json file
try {
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_APPEND);
fos.write(myJSONString.getBytes());
fos.close();
//Log.d(TAG, "Written to file");
}
catch (Exception e)
{
Log.d(TAG, "cought");
e.printStackTrace();
}

Related

Uploading a .zip file as binary InputStream from REST service

I have developed a REST Service with RESTEasy 3.0.12 deployed on WildFly 9 to upload a file in local file system.
I was trying to upload a zip file (testing with POST MAN sending file as binary not multi-part) I could successfully upload CSV, TXT, file format but when I try to send a ZIP file it saves correctly in the local file system but when I try to unzip it says
Headers error
Unconfirmed start of archive
Warnings: headers error
There are some data after the end of the payload data
Code:
#Path("/uploadZip")
#POST
#Produces(MediaType.APPLICATION_JSON)
public Response uploadZip(#Context HttpServletRequest req, InputStream payload){
// save to filesystem local.
Writer wr = null;
String tempFileName = System.getProperty("java.io.tmpdir");
try {
wr = new BufferedWriter(new FileWriter(tempFileName));
IOUtils.copy(payload, wr, "UTF-8");
} catch (IOException e) {
return errorResponse;
} finally {
// closing writer and stream
IOUtils.closeQuietly(wr);
IOUtils.closeQuietly(payload);
}
...
}
Does anyone know how to save a good zip file?
***General information on your Headers error:
Zip files contain local headers and a central directory at the end of the file. I don't know the gruesome details--and I won't attempt to expand upon them, but if you're getting a headers error then your zip file is corrupt. I'm not sure what you mean by there is some data after the "payload data."
***Thoughts on your code: Let's think conceptually.
Your endpoint is capturing an InputStream object, which is the superclass of all InputStream objects that represent an input stream of bytes. Your file is essentially wrapped in an object that you can read from byte-for-byte. The first problem I see is that you declare a Writer to write those bytes from the InputStream. Remember--Readers and Writers are for writing character streams, Input and Output streams are for byte streams. This explains why your CSV and TXT files are successful. It is important to know that difference and remember it!
#Path("/uploadZip")
#POST
#Produces(MediaType.APPLICATION_JSON)
public Response uploadZip(#Context HttpServletRequest req, InputStream payload){
OutputStream fos = new FileOutputStream(new File("path/to/filename.zip");
try {
byte[] bufferSize = new byte[1024];
int i = 0;
while ((i = payload.read(bufferSize)) != -1) {
fos.write(buf, 0, i);
}
} catch (IOException e) {
return errorResponse;
} finally {
fos.close();
}
...
}
I am confident that it will work. Let me know if this gives you any trouble. Best of luck!

retrieve single image via its url in java

I have a problem and I hope that you can help me. I would appreciate any help from anyone. The problem is the following.
I have a camera that has an http service, and I am communicating with the camera using the http. So the problem is that I send http request and I have back an http response in which I have a binary jpeg data. But I do not know how to convert that data into picture.
So my question is how can I convert that binary data into picture with java?
This is one example
http request:
GET (url to picture)
http response:
binary jpeg data
I thank to all of you in forward for all of your help.
URL url = new URL("http://10.10.1.154" + GETIMAGESCR());
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String inputLine;
// while ((inputLine = in.readLine()) != null){
// inputLine = in.readLine();
File file = new File("D:\\alphas\\proba.bin");
boolean postoi = file.createNewFile();
FileWriter fstream = new FileWriter("D:\\alphas\\proba.bin");
BufferedWriter out = new BufferedWriter(fstream);
while ((inputLine = in.readLine()) != null){
out.write(in.readLine());
// out.close();
// System.out.println("File created successfully.");
System.out.println(inputLine);
}
System.out.println("File created successfully.");
out.close();
in.close();
With this code I am getting the binary JPEG data, and I menage to save the data in a file. So the question is now how to convert this data into picture, or how to create the picture?
By the way I do not need to save the file that I get, if you have a way to create the picture directly it would be the best way
retrieve single image via its url in java
you just need to write byte data of image in response and set the proper content type, It will serve image from servlet
try {
URL url = new URL("http://site.com/image.jpeg");
java.awt.Image image = java.awt.Toolkit.getDefaultToolkit().createImage(url);
} catch (MalformedURLException e) {
} catch (IOException e) {
}
Am I missing something or are you just looking for this:
new ImageIcon(new URL("http://some.link.to/your/image.jpg"));
If you need to save the data from the URL, then just read the bytes from the corresponding InputStream and write the read bytes to a FileOutputStream:

Transmission of files through Socket or HTTP, between Android devices and desktops

I have custom socket client server data (file or text) transmission code. Now when I transfer binary files, some bytes convert onto out of range characters. So I send them in hex string. That works. But for another problem this is not the solution. This has a performance problems as well.
I took help from Java code To convert byte to Hexadecimal.
When I download images from the net, same thing happens. Some bytes change into something else. I have compared bytes by bytes.
Converting into String show ? instead of the symbol. I have tried readers and byte array input stream. I have tried all the examples on the net. What is the mistake I could be doing?
My Code to save bytes to file:
void saveFile(String strFileName){
try{
URL url = new URL(strImageRoot + strFileName);
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
BufferedWriter bw = new BufferedWriter(new FileWriter(strImageDownloadPath + strFileName));
String line = null;
while ( (line = reader.readLine()) != null) {
bw.write(line);
}
}catch(FileNotFoundException fnfe){
System.out.println("FileNotFoundException occured!!!");
}catch(IOException ioe){
}catch(Exception e){
System.out.println("Exception occured : " + e);
}finally{
System.out.println("Image downloaded!!!");
}
}
i had a similar issue when i was building a Socket client server application. The bytes would be some weird characters and i tried all sorts of things to try and compare them. Then i came across a discussion where some1 pointed out to me that i should use a datainputstream, dataoutstream and let that do the conversion to and from bytes. that worked for me totally. i never touched the bytes at all.
use this code
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File (root.getAbsolutePath() + "/image");
if(dir.exists()==false) {
dir.mkdirs();
}
URL url = new URL("http://4.bp.blogspot.com/-zqJs1fVcfeY/TiZM7e-pFqI/AAAAAAAABjo/aKTtTDTCgKU/s1600/Final-Fantasy-X-Night-Sky-881.jpg");
//URL url = new URL(DownloadUrl);
//you can write here any link
File file = new File(dir,"Final-Fantasy-X-Night-Sky-881.jpg");
long startTime = System.currentTimeMillis();
//Open a connection to that URL.
URLConnection ucon = url.openConnection();
//* Define InputStreams to read from the URLConnection.
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
//* Read bytes to the Buffer until there is nothing more to read(-1).
ByteArrayBuffer baf = new ByteArrayBuffer(6000);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
//Convert the Bytes read to a String.
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.flush();
fos.close();
You should take the help of this link: How to encode decode in base64 in Android.
You can send byte array obtained from a file as string by encoding into Base64. This reduces the amount of data transmitted as well.
At the receiving end just decode the string using Base64 and obtain byte array.
Then you can use #Deepak Swami's solution to save bytes in file.
I recently found out that PHP service APIs do not know about what is byte array. Any String can be byte stream at the same time, so the APIs expect Base64 string in the request parameter. Please see the posts:
String to byte array in php
Passing base64 encoded strings in URL
Hence Base64 has quite importance as also it allows you to also save byte arrays in preferences, and increases performance if you have to send file data across network using Serialization.
Happy Coding :-)

How to have ASP.Net Webpage read bytes from Java Android client?

I'm trying to upload images to External MS SQL database using android phone. I'm using Java HttpClient to send array of bytes to web server or web page. I don't know how I should approach this. The web page should be in ASP.net. I'm fairly new to ASP.Net. I did intensive research on how to read in a byte array using ASP.Net and still don't have an answer. I want my webpage or server to read in the bytes and store them into database.
Below is my Java function (it is not tested yet since I don't have a way to read bytes yet) that I want to use to send the bytes. But I have no idea how to read them in on website side. Any suggestions would be appreciated. If you guys see that I'm doing something wrong also it would be appreciated if you let me know and tell me how I should fix it. Please be specific since I'm really new to this and don't really know much about web pages. Thanks.
private void sendImagesToServer() throws Exception
{
ImageItem image;
HttpURLConnection conn = null;
ImageIterator iterator;
DataOutputStream dos;
byte[] byteArray;
iterator = new ImageIterator(imageAdapter);
String uploadUrl;
while(iterator.hasNext())
{
image = iterator.getNext();
Uri uri = Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, Integer.toString(image.id));
Bitmap bmp=BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byteArray = stream.toByteArray();
uploadUrl = "http://localhost:63776/SQLScript.aspx";
// Send request
try {
// Configure connection
URL url = new URL(uploadUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("PUT");
conn.setRequestProperty("Connection", "Keep-Alive");
dos = new DataOutputStream(conn.getOutputStream());
dos.write(byteArray, 0, byteArray.length);
dos.flush();
dos.close();
// Read response
try {
if (conn.getResponseCode() == 200) {
Toast.makeText(this,"Yay, We Got 200 as Response Code",Toast.LENGTH_SHORT).show();
}
} catch (IOException ioex) {
ioex.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} finally{
}
}
}
If you've verified the bytes are getting out of the Java fine, check this question, it may have what you need.
Read Http Request into Byte array
As far as getting it into a database, you could save files in a binary database (different MSSQL setup) or convert to strings and back again as necessary.

how to copy zip and other files in REST web service using java

Do anyone know how to copy data in zip file, jar file , binary file and others in REST web service using java? I write a web service method to copy file using FileInputStream , but it can only copy file type.
thanks
I'd recommend using apache httpclient for this. Your code might look something like (note, make sure you're using version 4.x or higher):
HttpClient client = new DefaultHttpClient();
HttpRequestBase httpMethod = httpMethod = new HttpGet(myUrlString);
httpMethod.setHeader("Accept", "application/zip");
HttpResponse response = httpClient.execute(httpMethod);
int statusCode = response.getStatusLine().getStatusCode();
if(statusCode != 200) {
throw new Exception("Bad return status code of: "+statusCode);
}
HttpEntity entity = response.getEntity();
if( entity != null) {
FileOutputStream fos = new FileOutputStream("myFile.zip");
int nextByte=0;
InputStream cis = entity.getContent();
try {
while( (nextByte = cis.read()) >= 0) fos.write(nextByte);
} finally {
fos.close();
cis.close();
}
}
I haven't compiled this, but you could probably get it going without too much issue (feel free to edit my comment and correct the code if you try to compile this and there are errors). Also note, this code should generically work for downloading anything from a web request (after changing the "Accept" header).

Categories