How to send byte array from Android device to servlet - java

I need to send some byte array from android device to Servlet. For this I try to use next code:
Servlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
DataInputStream in = new DataInputStream((InputStream)request.getInputStream());
response.setContentType("text/plain");
byte[] buffer = new byte[1024];
int len = 0;
File file;
file=new File(getServletContext().getRealPath("/POST_LOG!!!!.txt"));
if(!file.exists()){
file.createNewFile();
}
while ((len = in.read(buffer)) > 0) {
FileOutputStream fos = new FileOutputStream(getServletContext().getRealPath("/POST_LOG!!!!.txt"), true);
fos.write(buffer);
fos.close();
}
PrintWriter out = response.getWriter();
out.write("Done");
out.close();
Device side :
URL uploadUrl;
try {
uploadUrl = new URL(url);
HttpURLConnection c = (HttpURLConnection) uploadUrl
.openConnection();
c.setRequestMethod("POST");
c.setDoInput(true);
c.setDoOutput(true);
c.setUseCaches(false);
c.connect();
OutputStream out = c.getOutputStream();
for (int i = 0; i < 1000; i++) { // generate random bytes for
// uploading
byte[] buffer = new byte[256];
for (int j = 0; j < 256; j++) {
Random r = new Random();
buffer[j] = (byte) r.nextInt();
}
out.write(buffer);
out.flush();
}
out.close();
} catch (Exception e) {
MessageBox("Error. " + e.toString());
}
return (long) 0;
}
I dont understand why this code doesnt work. When I try to debug my POST method it even not called. I will grateful for your examples

I found the solution. I just changed my device-side code using custom InputStream.
Device side :
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new InputStreamEntity(new MyInputStream(),
4096 * 1024 * 10));
HttpResponse response = null;
try {
response = httpClient.execute(httpPost);
} catch (ClientProtocolException e) {
e.printStackTrace();
httpPost.abort();
} catch (IOException e) {
e.printStackTrace();
httpPost.abort();
}

You have a lot of options:
send the byte values: 125,11,25,40 (that's a dumb option)
send it base64- or hex- encoded, and then decode it (use apache commons-codec)
submit it as multipart/form-data

Related

s3 only allows uploading from one folder

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);
}

Missing Bottom part of image using getResponse().getOutputStream().write

i got the image from post response
PostMethod post = new PostMethod(action);
HttpClient httpClient = createHttpClient();
........
httpClient.executeMethod(post);
try {
log.info("post successfully");
String contentType = post.getResponseHeader("Content-type").getValue();
int contentLength = (int) post.getResponseContentLength();
byte[] responseBody = FileUtils.convertInputStreamtoByteArray(post.getResponseBodyAsStream());
log.info("get response sucessfully : size "+ responseBody.length +" contentLength " + contentLength);
return new ReturnBean(null, responseBody,contentType,contentLength);
} catch (Exception e) {
log.error(e.getMessage());
log.error(e.getStackTrace());
e.printStackTrace();
throw new ResponseFailedException(e.getMessage());
}
this is how i convert inputstream to byte array.
public static byte[] convertInputStreamtoByteArray(InputStream is){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
byte[] buf = new byte[1024];
int i = 0;
while ((i = is.read(buf)) >= 0) {
baos.write(buf, 0, i);
}
is.close();
} catch (Exception ex) {
ex.printStackTrace();
}
return baos.toByteArray();
}
this is how i return the image as a response.
byte[] imageSource = (byte[])returnStream.getBean();
log.info("imageSource " + imageSource.length);
getResponse().setContentType((String) returnStream.getBean2());
getResponse().setContentLength((Integer) returnStream.getBean3());
getResponse().getOutputStream().write(imageSource);
getResponse().getOutputStream().flush();
i was able to print out the image but im having a problem because the bottom part of it is missing . i checked the size of byte that i got and it is equal to the size of actual image.
when i used IOUtils.copyLarge(); instead of my method convertInputStreamtoByteArray
ServletOutputStream outputStream = getResponse().getOutputStream();
InputStream inputStream = (InputStream) returnStream.getBean();
IOUtils.copyLarge(inputStream , outputStream);
it works . i dont know what happen because i used it a while ago and it didnt work.

Zlib decompression in java not working

I am compressing a string in PHP 5.4.4-14+deb7u7 using
$cdat = gzcompress($dat, 9);
http://php.net/manual/en/function.gzcompress.php
Then in android/java I want to decompress it, from here:
Android: decompress string that was compressed with PHP gzcompress()
I am using:
public static String unzipString(String zippedText) {
String unzipped = null;
try {
byte[] zbytes = zippedText.getBytes("ISO-8859-1");
// Add extra byte to array when Inflater is set to true
byte[] input = new byte[zbytes.length + 1];
System.arraycopy(zbytes, 0, input, 0, zbytes.length);
input[zbytes.length] = 0;
ByteArrayInputStream bin = new ByteArrayInputStream(input);
InflaterInputStream in = new InflaterInputStream(bin);
ByteArrayOutputStream bout = new ByteArrayOutputStream(512);
int b;
while ((b = in.read()) != -1) {
bout.write(b);
}
bout.close();
unzipped = bout.toString();
} catch (IOException e) {
}
return unzipped;
}
But when I tried it, it decompressed into an empty string, when the downloaded compressed string in android was really long.
The downloaded string was like
x�͜{o�8�a`�= �!�����[��K!(6c�E�$��]�)�HF��F\!����ə���L�LNnH]Lj٬T��M���f�'�u#�*_�7'�S^�w��*kڼn�Yޚ�I��e$.1C��~�ݟ��F�A�_Mv_�R͋��ܴ�Z^L���sU?A���?�׮�ZVmֽ6��>�B��C�M�*����^�sٸ�j����������?�"_�j�ܣY�E���h0�g��w[=&�D �oht=>�l�?��Po";`.�e�E�E��[���������sq��0���i]��������zUL�O{П��ժ�k��b�.&7��-d1_��ۣ�狝�y���=F��K!�rC�{�$����c�&9ޣH���n�x�
Does anyone know what the problem is?
Thanks.
public static Pair<String,Integer> GetHTTPResponse(String url, List<NameValuePair> urlparameters) {
String responseVal = null;
int responseCode = 0;
try {
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = TIMEOUT_SECONDS * 1000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = TIMEOUT_SECONDS * 1000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpClient client = new DefaultHttpClient(httpParameters);
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(urlparameters));
HttpResponse response = client.execute(httppost);
responseCode = response.getStatusLine().getStatusCode();
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
responseVal = Common.GetStringFromBufferedReader(rd);
Log.d("SERVER", responseVal);
}
catch (Exception e) {
responseCode = 0;
}
if (responseVal != null) {
responseVal = Common.unzipString(responseVal);
}
return new Pair<String, Integer>(responseVal, responseCode);
}
You can't use
BufferedReader rd =
new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
responseVal = Common.GetStringFromBufferedReader(rd);
As InputStreamReader's Javadoc notes,
An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and decodes them into characters using a specified charset.
Instead, you could use HttpEntity.writeTo(OutputStream) and a ByteArrayOutputStream like
ByteArrayOutputStream baos = new ByteArrayOutputStream();
response.getEntity().writeTo(baos);
byte[] content = baos.toByteArray();
Then you can directly pass the content to your function in that byte[], and never silently swallow an Exception.
public static String unzipString(byte[] zbytes) {
String charsetName = "ISO-8859-1";
String unzipped = null;
try {
// Add extra byte to array when Inflater is set to true
byte[] input = new byte[zbytes.length + 1];
System.arraycopy(zbytes, 0, input, 0, zbytes.length);
input[zbytes.length] = 0;
ByteArrayInputStream bin = new ByteArrayInputStream(input);
InflaterInputStream in = new InflaterInputStream(bin);
ByteArrayOutputStream bout = new ByteArrayOutputStream(512);
int b;
while ((b = in.read()) != -1) {
bout.write(b);
}
bout.close();
unzipped = bout.toString(charsetName);
} catch (IOException e) {
e.printStackTrace();
}
return unzipped;
}

How to read byte array in php

I am sending a mp3 file using the following code to a server.In server I want a php code to receive this byte array of mp3 and convert it into file and store it there.
try {
final ByteArrayOutputStream out = new ByteArrayOutputStream();
File file = new File(Environment.getExternalStorageDirectory()+ "/my.mp3");
final InputStream in = new FileInputStream(file);
final byte[] buf = new byte[2048];
int n;
while ((n = in.read(buf)) >= 0) {
out.write(buf, 0, n);
}
final byte[] data = out.toByteArray();
String urlString = "http://10.0.0.56/upload.php";
HttpPost postRequest = new HttpPost(urlString);
postRequest.setEntity(new ByteArrayEntity(data));
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(postRequest);
HttpEntity entity = response.getEntity();
InputStream ins = entity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(ins));
String temp_str;
StringBuilder sb = new StringBuilder();
while((temp_str = br.readLine()) != null) {
sb.append(temp_str);
}
Log.e("response", sb.toString());
} catch (Exception e) {
// handle exception here
Log.e(e.getClass().getName(), e.getMessage());
return "exception";
}
Any one know how to read the mp3 file using php.
Your upload.php could look something like this:
$mp3_bin = file_get_contents('php://input');
file_put_contents( '/path/to/my/mp3', $mp3_bin );
Short and sweet ;)
Edit:
# A bit of golfing gives a one liner:
file_put_contents('/path/to/my.mp3', file_get_contents('php://input'));

Error while downloading the zip file from server to device?

I am using this code to download zip file from server
private static InputStream OpenHttpConnection(String urlString)
throws IOException
{
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try{
System.out.println("OpenHttpConnection called");
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
httpConn.setRequestProperty("content-type", "binary/data");
httpConn.connect();
response = httpConn.getResponseCode();
System.out.println("response is"+response);
System.out.println(HttpURLConnection.HTTP_OK);
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
System.out.println("Connection Ok");
return in;
}
}
catch (Exception ex)
{
throw new IOException("Error connecting");
}
return in;
}
and
private static void saveToInternalSorage(InputStream in,String filename,Context ctx){
//fos =openFileOutput(filename, Context.MODE_WORLD_READABLE);
try {
// System.out.println("mypath = "+mypath);
//fos = new FileOutputStream(mypath);
FileOutputStream fos = (ctx).openFileOutput(filename, Context.MODE_WORLD_READABLE);
byte[] buffer=new byte[1024];
int len1 ;
while ( (len1 = in.read(buffer) )!=-1 ) {
fos.write(buffer);
}
// Use the compress method on the BitMap object to write image to the OutputStream
} catch (Exception e) {
e.printStackTrace();
}
}
The zip file which is downloaded is corrupted , the actual size of the file is 3.5kb but the downloaded file is of 5kb .What is the problem with the code please help?
This
while ( (len1 = in.read(buffer) )!=-1 ) {
fos.write(buffer);
}
You are writing the entire buffer in each iteration (1024 bytes). You should only write len1 bytes (number of bytes read).
On a side-note, you may want to look at using some higher level abstraction libraries for stuff like HTTP and stream manipulation. Apache Commons HttpComponents and Commons IO for instance.
httpConn.setDoOutput(false);
httpConn.setRequestProperty("Content-Type", "application/octet-stream");
httpConn.setRequestProperty("Content-Length", String.valueOf(file.length());
while (... > 0) {
fos.write(buffer, 0, len1);
fos.close();
Write only the bytes which are filled in the buffer i.e only len1 bytes. It will solve your problem as if the buffer is not filled completely, we will write only those bytes which are read.
while ( (len1 = in.read(buffer) )!=-1 ) {
fos.write(subArray(buffer,len1));
}
//Method to create su-array
public byte[] subArray(byte[] arr, int length) {
byte temp[] = new byte[length];
for (int i = 0; i < length; i++) {
temp[i] = arr[i];
}
return temp;
}

Categories

Resources