How to upload image from android to java - java

I am developing a software in which images should be upload from android to java. so far I have developed the following client on android:
String url=params[0];
String filePath=params[1];
File file=new File(filePath);
MultipartEntityBuilder multipartEntityBuilder=MultipartEntityBuilder.create();
multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
multipartEntityBuilder.addPart("file", new FileBody(file));
HttpPut httpPut=new HttpPut(url);
HttpClient httpclient = new DefaultHttpClient();
httpPut.setEntity(multipartEntityBuilder.build());
HttpResponse response;
try {
response = httpclient.execute(httpPut);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String result= convertStreamToString(instream);
instream.close();
return result;
}
} catch (Exception e) {
}
return null;
}
and the server is:
String path=Server.imagesPath+Utilities.getRandomString(10)+".jpg";
InputStream inputStream= arg0.getRequestBody();
File file=new File(path);
Files.copy(inputStream, file.toPath());
String response="OK";
try{
arg0.sendResponseHeaders(200, response.length());
OutputStream outputStream=arg0.getResponseBody();
outputStream.write(response.getBytes());
outputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The image is completely copied to the server but it is damaged and it can not be viewed. What is the problem?

It looks as though the upload is being done as a multipart form, which allows you to insert images as part of the data being sent; but the server is reading it as a pure octet stream rather than a multipart form.
You need to choose one or the other. Either interpret it as form data on the server, or just send the data as a stream rather than as form data.
I'd suggest having a look at Apache Commons FileUpload, which will simplify lots of this.

You can also use multiple data part entity for image uploading
you can see complete demo here: http://niravranpara.blogspot.in/2012/11/upload-video-in-server.html

I could finally solve the problem using this article:
Android Code to Upload & Download large files to server
the code I used on the Android was:
String urlString=params[0];
String path=params[1];
File file=new File(path);
int maxBufferSize=1024;
URL url=null;
try {
url=new URL(urlString);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpURLConnection connection=null;
try {
connection = (HttpURLConnection) url.openConnection();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
try {
connection.setRequestMethod("PUT");
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
connection.setRequestProperty("Content-Type", "image/jpg");
OutputStream outputStream=null;
FileInputStream fileInputStream=null;
byte[] buffer;
int bytesRead,bytesAvailable,bufferSize;
try {
outputStream=connection.getOutputStream();
fileInputStream=new FileInputStream(file);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while(bytesRead > 0){
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
int serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
Log.d("test Response Code ",Integer.toString(serverResponseCode));
Log.d("test Response Message ", serverResponseMessage);
} catch (IOException e) {
Log.d("test", e.getMessage());
}

Related

Download File from Direct Download URL

I'm trying to download the following the following file, with this link that redirects you to a direct download: http://www.lavozdegalicia.es/sitemap_sections.xml.gz
I've done my own research, but all the results I see are related to HTTP URL redirections
[3xx] and not to direct download redirections (maybe I'm using the wrong terms to do the research).
I've tried the following pieces of code (cite: https://programmerclick.com/article/7719159084/ ):
// Using Java IO
private static void downloadFileFromUrlWithJavaIO(String fileName, String fileUrl) {
BufferedInputStream inputStream = null;
FileOutputStream outputStream = null;
try {
URL url = new URL(fileUrl);
inputStream = new BufferedInputStream(url.openStream());
outputStream = new FileOutputStream(fileName);
byte data[] = new byte[1024];
int count;
while ((count = inputStream.read(data, 0, 1024)) != -1) {
outputStream.write(data, 0, count);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
// Using Apache common IO
private static void downloadFileFromUrlWithCommonsIO(String fileName, String fileUrl) {
try {
FileUtils.copyURLToFile(new URL(fileUrl), new File(fileName));
} catch (IOException e) {
e.printStackTrace();
}
}
// Using NIO
private static void downloadFileFromURLUsingNIO(String fileName, String fileUrl) {
try {
URL url = new URL(fileUrl);
ReadableByteChannel readableByteChannel = Channels.newChannel(url.openStream());
FileOutputStream fileOutputStream = new FileOutputStream(fileName);
fileOutputStream.getChannel().transferFrom(readableByteChannel, 0, Long.MAX_VALUE);
fileOutputStream.close();
readableByteChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
But the result I get with any of the three options is an empty file, my thoughts are that the problem is related to the file being a .xml.gz because when I debug it the inputStream doesn't seem to have any content.
I ran out of options, anyone has an idea of how to handle this case, or what would be the correct terms I should use to research about this specific case?
I found a solution, there's probably a more polite way of achieving the same result but this worked fine for me:
//Download the file and decompress it
filecount=0;
URL compressedSitemap = new URL(urlString);
HttpURLConnection con = (HttpURLConnection) compressedSitemap.openConnection();
con.setRequestMethod("GET");
if (con.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP || con.getResponseCode() == HttpURLConnection.HTTP_MOVED_PERM) {
String location = con.getHeaderField("Location");
URL newUrl = new URL(location);
con = (HttpURLConnection) newUrl.openConnection();
}
String file = "/home/user/Documentos/Decompression/decompressed" + filecount + ".xml";
GZIPInputStream gzipInputStream = new GZIPInputStream(con.getInputStream());
FileOutputStream fos = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int len = 0;
while ((len = gzipInputStream.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
filecount++;
Two things to note:
When I was trying to do HTTPGet the url that was a redirect, the response code was 301 or 302 (depending on the example I used), I overcame this problem with the if check, that follows the redirect and aims to the downloaded file.
Once aiming the file, to get the content of the compressed file I found the GZIPInputStream package, that allowed me to get an inputStream directly from the compressed file and dump it on an xml file, that saved me the time of doing it on three steps (decompress, read, copy).

Error writing to server

I am uploading a file from one server to another server using a Java Program 'POST' method. But I am getting below exception.
java.io.IOException: Error writing to server
at sun.net.www.protocol.http.HttpURLConnection.writeRequests(HttpURLConnection.java:582)
at sun.net.www.protocol.http.HttpURLConnection.writeRequests(HttpURLConnection.java:594)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1216)
at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:379)
at com.test.rest.HttpURLConnectionExample.TransferFile(HttpURLConnectionExample.java:107)
at com.test.rest.HttpURLConnectionExample.main(HttpURLConnectionExample.java:44)
I have other method who will authenticate with server. Which will be be called from below code. When I am getting response from server, I am getting above exception. To Transfer a file to server I have written below method. My sample code is below:
public static void TransferFile(){
String urlStr = "http://192.168.0.8:8600/audiofile?path=1/622080256/virtualhaircut.mp3";
File tempFile = new File("/home/MyPath/Workspace/Sample/virtualhaircut.mp3");
BufferedWriter br=null;
HttpURLConnection conn = null;
URL url;
try {
url = new URL(urlStr);
AuthenticationUser();
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", new MimetypesFileTypeMap().getContentType(tempFile.getName()));
} catch (MalformedURLException e1) {
System.out.println("Malformed");
e1.printStackTrace();
} catch (ProtocolException e) {
System.out.println("Protocol");
e.printStackTrace();
} catch (IOException e) {
System.out.println("IO");
e.printStackTrace();
}
System.out.println("line 69");
FileInputStream fis;
OutputStream fos;
try {
System.out.println("line 75");
System.out.println("line 77");
fis = new FileInputStream(tempFile);
fos = conn.getOutputStream();
byte[] buf = new byte[1024 * 2];
int len = 0;
System.out.println("line 80");
while ((len = fis.read(buf)) > 0) {
fos.write(buf, 0, len);
System.out.println("line 85");
}
System.out.println("line 87");
buf = null;
fos.flush();
fos.close();
fis.close();
}catch (FileNotFoundException e) {
System.out.println("");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (conn.getResponseCode() == 200) {
System.out.println("here");
}
} catch (IOException e) {
e.printStackTrace();
}
}
It is possible that the error ocurred because the receiving server closed the connection, maybe because your file exceeded the size limit. Have you tested with small files?

android : How can I compress a bitmap in download

my application downloads a bitmap :
public byte[] getUrlImgContent(String urlstring) throws IOException
{
byte[] imageRaw = null;
URL url = new URL(urlstring);
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.setUseCaches(false);
urlConnection.connect();
if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK)
{
try
{
InputStream in = new BufferedInputStream(
urlConnection.getInputStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
int c;
while ((c = in.read()) != -1)
{
out.write(c);
}
out.flush();
imageRaw = out.toByteArray();
urlConnection.disconnect();
in.close();
out.close();
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return imageRaw;
}
return null;
}
and i'm directly converting it to bitmap and showing it in a zoomable-imageview
the problem : the application crashes if the file size is too big
what should I do to reduce the image's size ? (format : jpg)

Difficulty in receiving response from HTTP client

I am writing an application which will send XML over HTTP to a server, and receive XML as the response. I am able to send XML to the server but not able to receive the response.
This is my client code:
public void sendXMLToServer(){
System.out.println("sendXMLToServer");
String strURL = "http://localhost:9080/MockServerMachine/sendXMLPost";
// Get file to be posted
String strXMLFilename = "output.xml";
File input = new File(strXMLFilename);
// Prepare HTTP post
System.out.println("junaud url "+ strURL);
PostMethod post = new PostMethod(strURL);
// Request content will be retrieved directly
// from the input stream
// Per default, the request content needs to be buffered
// in order to determine its length.
// Request body buffering can be avoided when
// content length is explicitly specified
try {
post.setRequestHeader("Content-type","application/xml");
post.setRequestHeader("Accept","application/xml");
post.setRequestEntity(new InputStreamRequestEntity(
new FileInputStream(input), input.length()));
HttpClient httpclient = new HttpClient();
int result = httpclient.executeMethod(post);
String xmlResponse = post.getResponseBodyAsString();
// Display status code
System.out.println("Response status code jun: " + result);
// Display response
System.out.println("Response body: ");
System.out.println(post.getResponseBodyAsString());
post.releaseConnection();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (HttpException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
This is the server side:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//InputStream in = request.getInputStream();
//URL xmlUrl = new URL(request.getRequestURL().toString());
//InputStream in = xmlUrl.openStream();
response.setContentLength(100);
// PostMethod po = new PostMethod(request.getRequestURL().toString());
// System.out.println("kikmk = "+po.getRequestEntity());
try {
// read this file into InputStream
//InputStream inputStream = new FileInputStream("c:\\file.xml");
InputStream inputStream = request.getInputStream();
// write the inputStream to a FileOutputStream
OutputStream out = new FileOutputStream(new File("c:\\junaidAhmedJameel.xml"));
int read = 0;
byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
System.out.println(new String (bytes));
System.out.println(read);
out.write(bytes, 0, read);
}
inputStream.close();
out.flush();
out.close();
System.out.println("New file created!");
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
Can anyone help me out here? Any sample client/server example for sending XML over HTTP would be great.
Ah, spotted it. Look here:
OutputStream out = new FileOutputStream(new File("c:\\junaidAhmedJameel.xml"));
That's just going to write to the local disk. You're not writing any content to the response stream. It's not clear what you want to write to the response stream, but there's a conspicuous absence of calls to response.getWriter() or response.getOutputStream().
You're setting the content length to 100, but not actually sending any content. Note that hard-coding the content-length is almost certainly the wrong thing to do anyway... but it's definitely the wrong thing to do when you're not sending any content...
You never generate any response content in your server code. You just set the length to 100.

Error handling for URLConnection

I have this method that downloads .csv files from yahoo finance and saves them locally. It is accessed during a loop so it is downloading many files from a list. However sometimes a symbol is entered incorrectly, no longer exists, or the connection times out. How can I amend this method so that connection time outs are retried and incorrect symbols (meaning the url does not work) are just skipped over without ending the program?
public static void get_file(String symbol){
OutputStream outStream = null;
URLConnection uCon = null;
InputStream is = null;
String finance_url = "http://ichart.finance.yahoo.com/table.csv?s="+symbol;
String destination = "C:/"+symbol+"_table.csv";
try {
URL Url;
byte[] buf;
int ByteRead,ByteWritten=0;
Url= new URL(finance_url);
outStream = new BufferedOutputStream(new FileOutputStream(destination));
uCon = Url.openConnection();
is = uCon.getInputStream();
buf = new byte[size];
while ((ByteRead = is.read(buf)) != -1) {
outStream.write(buf, 0, ByteRead);
ByteWritten += ByteRead;
}
}catch (Exception e) {
System.out.println("Error while downloading "+symbol);
e.printStackTrace();
}finally {
try {
is.close();
outStream.close();
}catch (IOException e) {
e.printStackTrace();
}
}
}
Why not call the method again when an exception is thrown. You can narrow down the exception type to indicate when a retry should be initiated.
public static void get_file(String symbol){
OutputStream outStream = null;
URLConnection uCon = null;
InputStream is = null;
String finance_url = "http://ichart.finance.yahoo.com/table.csv?s="+symbol;
String destination = "C:/"+symbol+"_table.csv";
try {
URL Url;
byte[] buf;
int ByteRead,ByteWritten=0;
Url= new URL(finance_url);
outStream = new BufferedOutputStream(new FileOutputStream(destination));
uCon = Url.openConnection();
is = uCon.getInputStream();
buf = new byte[size];
while ((ByteRead = is.read(buf)) != -1) {
outStream.write(buf, 0, ByteRead);
ByteWritten += ByteRead;
}
}catch (Exception e) {
getFile(symbol);
}finally {
try {
is.close();
outStream.close();
}catch (IOException e) {
e.printStackTrace();
}
}
}

Categories

Resources