How to read byte array in php - java

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

Related

How do I download and save a Zip file using Java/Spring Boot code from a server?

I need to develop an API which can open connection to an URL which returns a ZIP file. This URL works perfectly fine when accessed from browser or Postman but when I try to access it from Java Code (tried HttpClient/RestTemplate etc) it returns an HTML file. I want to get the zip file and want to store it at particular directory.
HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
HttpGet request = new HttpGet(url);
logger.info("Request to Asset Store: URL " + request.getURI());
HttpResponse response = client.execute(request);
if (response != null) {
for (Header header : response.getAllHeaders()) {
System.out.println(header.getName() + " - " + header.getValue());
}
BufferedInputStream bis = new BufferedInputStream(response.getEntity().getContent());
final ZipInputStream is = new ZipInputStream(bis);
try {
ZipEntry entry;
while ((entry = is.getNextEntry()) != null) {
System.out.printf("File: %s Size %d Modified on %TD %n", entry.getName(),
entry.getSize(), new Date(entry.getTime()));
extractEntry(entry, is);
}
System.out.println("OUT");
} finally {
is.close();
}
}
private static void extractEntry(final ZipEntry entry, InputStream is) throws IOException {
String exractedFile = "D://" + entry.getName();
FileOutputStream fos = null;
try {
fos = new FileOutputStream(exractedFile);
final byte[] buf = new byte[2048];
int read = 0;
int length;
while ((length = is.read(buf, 0, buf.length)) >= 0) {
fos.write(buf, 0, length);
}
} catch (IOException ioex) {
fos.close();

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

HttpURLConnection output to byte array then to String

I'm reading a response from an HttpURLConnection object to a String like so:
HttpURLConnection conn = ...;
BufferedReader rd = new BufferedReader(new InputStreamReader(
conn.getInputStream());
StringBuilder sb = ...;
String line = "";
while ((line = rd.readLine()) != null) {
sb.append(line);
}
String asString = sb.toString();
If I want to read instead to a byte array first, then convert that byte array to a String, what's the right way to do it?
InputStream is = conn.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream(16384);
byte[] buf = new byte[512];
while (true) {
int len = in.read(buf);
if (len == -1) {
break;
}
baos.write(buf, 0, len);
}
byte[] out = baos.toByteArray();
// as a string:
String asString = new String(out);
but I'm not specifying the character in either case - are the two String outputs at the end of the examples equivalent?
Thanks

Not able to download file from internet url in java

i want to download a csv file from a internet url.
I have tried every code that i can find online and not able to download.
URL google = new URL("myurl");
ReadableByteChannel rbc = Channels.newChannel(google.openStream());
FileOutputStream fos = new FileOutputStream("C://excelsheet.csv");
fos.getChannel().transferFrom(rbc, 0, 1 << 24);
This code is not working
I used this function , it is not working too.
public stacvoid saveUrl(String filename, String urlString) throws MalformedURLException, IOException
{
BufferedInputStream in = null;
FileOutputStream fout = null;
try
{
in = new BufferedInputStream(new URL(urlString).openStream());
fout = new FileOutputStream(filename);
byte data[] = new byte[1024];
int count;
while ((count = in.read(data, 0, 1024)) != -1)
{
fout.write(data, 0, count);
}
}
finally
{
if (in != null)
in.close();
if (fout != null)
fout.close();
}
}
I tried a simple input stream on my url , that doesn't work too.
URL oracle = new URL("myurl");
URLConnection yc = oracle.openConnection();
BufferedReader br = new BufferedReader(new InputStreamReader(
yc.getInputStream()));
Now instead of myurl , if i type any other url , the bufferedreader does get data.
If I enter myurl in a browser i get a popup to save or download the csv file.
So the problem is not with an incorrrect "myurl"
Is it possible that the servelet/code running on "myurl" actually checks if the request is coming from a browser and only then sends the data.
Thanks everyone . Used httpclient and it works for me. Heres the code that downloads an csv file , saves it locally and then reads it and parses all the tokens.
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("your url to download");
HttpResponse response = httpclient.execute(httpget);
System.out.println(response.getProtocolVersion());
System.out.println(response.getStatusLine().getStatusCode());
System.out.println(response.getStatusLine().getReasonPhrase());
System.out.println(response.getStatusLine().toString());
HttpEntity entity = response.getEntity();
if (entity != null) {
FileOutputStream fos = new java.io.FileOutputStream("C://excelsheet.csv");
entity.writeTo(fos);
fos.close();
}
//create BufferedReader to read csv file
BufferedReader br = new BufferedReader( new FileReader("C://excelsheet.csv"));
String strLine = "";
StringTokenizer st = null;
int lineNumber = 0, tokenNumber = 0;
while( (strLine = br.readLine()) != null)
{
lineNumber++;
//break comma separated line using ","
st = new StringTokenizer(strLine, ",");
while(st.hasMoreTokens())
{
//display csv values
tokenNumber++;
System.out.println("Line # " + lineNumber +
", Token # " + tokenNumber
+ ", Token : "+ st.nextToken());
}
//reset token number
tokenNumber = 0;
}
}
catch (Exception e) {
System.out.println("insdie the catch part");
System.out.println(e.toString());
}
Have you tried the HttpClient lib?
I used it sometime ago to download a set of exams from a site automatically.

How to send byte array from Android device to servlet

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

Categories

Resources