Can someone help me with some file download code - android

Hi I am making a app that fetches a xml file and displays the results with a button labeled get it. I need help with when the button is clicked it will take the .pkg file url in the xml file and download it with some sort of progress reporting. Any help would be awesome thanks in advance. Here is what I have so far it has a error in the download code I tried maybe someone can fix this for me. I am stumped also the links are to .pkg files
package com.mypackagename;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.HttpsURLConnection;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.entity.StringEntity;
import org.apache.http.protocol.HttpContext;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import org.apache.http.util.ByteArrayBuffer;
import android.util.Log;
public class MainActivity extends ListActivity {
String XML_URL = "http://www.mysite.com/book.xml";
private DocumentBuilder docBuilder;
private Document doc;
private DocumentBuilderFactory docBuilderFactory;
private String bookImageUrl;
private int nodeListbooksLength;
private String bookId;
private String bookUrl;
private String bookDescription;
private String bookTitle;
ButtonListMenuAdapter notes;
ArrayList<Book> list;
TextView tv_title;
ImageView iv_logo;
private String Title;
Drawable booksImagesList[];
/** Called when the activity is first created. 1 */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv_title = (TextView) findViewById(R.id.TextView01);
iv_logo = (ImageView) findViewById(R.id.ImageView01);
list = new ArrayList<Book>();
parseXML();
notes = new ButtonListMenuAdapter(
this,
R.layout.book_row,
list );
setListAdapter( notes );
}
private void parseXML()
{
try{
Log.d("MainActivity", "Connecting Server");
InputStream inStream =openHttpConnection(XML_URL);
Log.d("MainActivity", "Fetching Data Completed");
if(inStream!=null){
docBuilderFactory = DocumentBuilderFactory.newInstance();
docBuilderFactory.setCoalescing(true);
docBuilder = docBuilderFactory.newDocumentBuilder();
docBuilder.isValidating();
doc = docBuilder.parse(inStream);
NodeList nodeListbookTitle = doc.getDocumentElement().getElementsByTagName("Title1");
if(nodeListbookTitle.getLength()>0){
Element elementbooktitile = (Element) nodeListbookTitle.item(0);
NodeList nodeListElementbooktitle = elementbooktitile.getChildNodes();
if(nodeListElementbooktitle.getLength()>0)
{
Title = ((Node) nodeListElementbooktitle.item(0)).getNodeValue();
Log.d("MainActivity", "Title:"+Title);
tv_title.setText(Title);
}
}
NodeList nodeListbookBanner = doc.getDocumentElement().getElementsByTagName("logo");
if(nodeListbookBanner.getLength()>0){
Element elementTeamBanner = (Element) nodeListbookBanner.item(0);
NodeList nodeListElementTeamBanner = elementTeamBanner.getChildNodes();
if(nodeListElementTeamBanner.getLength()>0)
{
bookImageUrl = ((Node) nodeListElementTeamBanner.item(0)).getNodeValue();
try {
DownloadFilesTask d = new DownloadFilesTask();
d.execute(new URL(bookImageUrl));
d.sendObjectImageView(iv_logo);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("ERROR getView", "EX::"+e);
}
Log.d("MainActivity", "bookImageUrl:"+bookImageUrl);
Log.d("MainActivity", "");
}
}
NodeList nodeListbook = doc.getDocumentElement().getElementsByTagName("Book");
Log.d("MainActivity","nodeListbook Length--"+nodeListbook.getLength());
nodeListbooksLength=nodeListbook.getLength();
booksImagesList = new Drawable[nodeListbooksLength+1];
if(nodeListbooksLength>0){
for(int v=0;v<nodeListbooksLength;v++){
Node nodebook = nodeListbook.item(v);
if (nodebook.getNodeType() == Node.ELEMENT_NODE){
Element elementbookResult = (Element) nodebook;
bookId=elementbookResult.getAttribute("bid");
Log.d("MainActivity","----in bookId- ->"+v+" "+bookId);
bookImageUrl=elementbookResult.getAttribute("bimg");
Log.d("MainActivity","--bookImageUrl--->"+bookImageUrl);
bookTitle=elementbookResult.getAttribute("bte");
Log.d("MainActivity","--bookTitle--->"+bookTitle);
bookDescription=elementbookResult.getAttribute("bsd");
Log.d("MainActivity","--bookDescription--->"+bookDescription);
bookUrl=elementbookResult.getAttribute("bph");
Log.d("MainActivity","--bookUrl:--->"+bookUrl);
list.add( new Book( bookId, bookImageUrl,bookTitle,bookDescription,bookUrl) );
}
}
}
}
}catch(Exception e){
Log.d("MainActivity", "parseXML:"+e);
}
}
private InputStream openHttpConnection(String urlStr) {
InputStream in = null;
int resCode = -1;
try {
Log.d("openHttpConnection", "URL:"+urlStr);
URL url = new URL(urlStr);
URLConnection urlConn = url.openConnection();
if (!(urlConn instanceof HttpURLConnection)) {
throw new IOException ("URL is not an Http URL");
}
Log.d("openHttpConnection", "httpConn:1");
HttpURLConnection httpConn = (HttpURLConnection)urlConn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; U; Linux "+"i686; en-US; rv:1.8.1.6) Gecko/20061201 Firefox/2.0.0.6 (Ubuntu-feisty)");
httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
Log.d("openHttpConnection", "setting requests and properties");
httpConn.connect();
Log.d("openHttpConnection", "Connected successfully");
resCode = httpConn.getResponseCode();
Log.d("openHttpConnection", "resCode"+resCode);
if (resCode == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
Log.d("openHttpConnection", "Fetchinf data done");
}
} catch (MalformedURLException e) {
e.printStackTrace();
Log.d("openHttpConnection", "1"+e);
} catch (IOException e) {
e.printStackTrace();
Log.d("openHttpConnection", ""+e);
}
return in;
}
private HttpClient httpClient;
private HttpPost httpPost;
private HttpResponse response;
private HttpContext localContext;
private String ret;
private InputStream postPage(String url, String data) {
InputStream is = null;
ret = null;
httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);
httpPost = new HttpPost(url);
response = null;
StringEntity tmp = null;
httpPost.setHeader("User-Agent", "Mozilla/5.0 (X11; U; Linux " +
"i686; en-US; rv:1.8.1.6) Gecko/20061201 Firefox/2.0.0.6 (Ubuntu-feisty)");
httpPost.setHeader("Accept", "text/html,application/xml," +
"application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
try {
tmp = new StringEntity(data,"UTF-8");
} catch (UnsupportedEncodingException e) {
System.out.println("HTTPHelp : UnsupportedEncodingException : "+e);
}
httpPost.setEntity(tmp);
try {
response = httpClient.execute(httpPost,localContext);
} catch (ClientProtocolException e) {
System.out.println("HTTPHelp : ClientProtocolException : "+e);
} catch (IOException e) {
System.out.println("HTTPHelp : IOException : "+e);
}
ret = response.getStatusLine().toString();
HttpEntity he = response.getEntity();
try {
InputStream inStream = he.getContent();
is = inStream;
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return is;
}
class Book
{
public String getBookId() {
return bookId;
}
public String getBookImageUrl() {
return bookImageUrl;
}
public String getBookTitle() {
return bookTitle;
}
public String getBookDescription() {
return bookDescription;
}
public String getBookUrl() {
return bookUrl;
}
private String bookId;
private String bookImageUrl;
private String bookTitle;
private String bookDescription;
private String bookUrl;
public Book(String bookId, String bookImageUrl, String bookTitle,String bookDescription, String bookUrl) {
this.bookId = bookId;
this.bookImageUrl = bookImageUrl;
this.bookTitle = bookTitle;
this.bookDescription = bookDescription;
this.bookUrl = bookUrl;
}
}
public class ButtonListMenuAdapter extends BaseAdapter {
public static final String LOG_TAG = "ButtonListAdapter";
private Context context;
private List<Book> menuList;
private int rowResID;
public ButtonListMenuAdapter(MainActivity context, int rowResID,
ArrayList<Book> menuList) {
// TODO Auto-generated constructor stub
this.context = context;
this.rowResID = rowResID;
this.menuList = menuList;
}
public int getCount() {
return menuList.size();
}
public Object getItem(int position) {
return menuList.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
final Book row = menuList.get(position);
LayoutInflater inflater = LayoutInflater.from( context );
View v = inflater.inflate( rowResID, parent, false );
TextView tv_title = (TextView)v.findViewById(R.id.Text_book_title);
tv_title.setText(row.getBookTitle());
TextView tv_desc = (TextView)v.findViewById(R.id.Text_Book_Desc);
tv_desc.setText(row.getBookDescription());
ImageView iv_book_img = (ImageView)v.findViewById(R.id.Image_book);
if(booksImagesList[position]==null)
{
try {
DownloadFilesTask d = new DownloadFilesTask();
d.execute(new URL(row.getBookImageUrl()));
d.sendObjectImageView(iv_book_img,position);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("ERROR getView", "EX::"+e);
}
}
else
{
iv_book_img.setImageDrawable(booksImagesList[position]);
Log.d("Not","Reloaded");
}
Button b_get_book = (Button)v.findViewById(R.id.Button01);
b_get_book.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View v) {
private final String PATH = "/mnt/sdcard/"; //put the downloaded file here
public void DownloadFromUrl(String bookUrl, String fileName) { //this is the downloader method
try {
URL url = new URL("http://mysite.com/" + bookUrl); //you can write here any link
File file = new File(fileName);
long startTime = System.currentTimeMillis();
Log.d("ImageManager", "download begining");
Log.d("ImageManager", "download url:" + url);
Log.d("ImageManager", "downloaded file name:" + fileName);
/* 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(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
/* Convert the Bytes read to a String. */
FileOutputStream fos = new FileOutputStream(PATH+file);
fos.write(baf.toByteArray());
fos.close();
Log.d("ImageManager", "download ready in"
+ ((System.currentTimeMillis() - startTime) / 1000)
+ " sec");
} catch (IOException e) {
Log.d("ImageManager", "Error: " + e);
}
}
}
});
return v;
}
}
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
ImageView iv;
int id;
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
downloadDrawable(urls[0].toString());
return totalSize;
}
public void sendObjectImageView(ImageView ivLogo) {
// TODO Auto-generated method stub
this.iv = ivLogo;
id = -1;
}
public void sendObjectImageView(ImageView iv,int id) {
// TODO Auto-generated method stub
this.iv = iv;
this.id = id;
}
protected void onProgressUpdate(Integer... progress) {
Log.d("DownloadFilesTask", "onProgressUpdate"+progress[0]);
}
protected void onPostExecute(Long result) {
Log.d("DownloadFilesTask", "onPostExecute"+result);
if(d!=null && iv!=null)
{
iv.setImageDrawable(d);
if(id!=-1)
booksImagesList[id] = d;
}
}
private Drawable d;
public Drawable downloadDrawable(String imageUrl) {
try {
Log.d("downloadDrawable", "Starting Connection");
URL url = new URL(imageUrl);
URLConnection conn = url.openConnection();
conn.connect();
Log.d("downloadDrawable", "Connection Created Successfully");
InputStream is = conn.getInputStream();
Log.d("downloadDrawable", "InputStream created Successfully");
d = Drawable.createFromStream(is, url.toString());
Log.d("downloadDrawable", "Drawable created Successfully");
is.close();
} catch (IOException e) {
Log.d("ERROR3", "Ex::"+e);
}
return d;
}
}
}

this is a typical http connection.
URL url = new URL(strUrl);
HttpURLConnection urlConn = (HttpURLConnection) url
.openConnection();
InputStream is = urlConn.getInputStream();
final int MAX_LENGTH = 10000;
byte[] buf = new byte[MAX_LENGTH];
int total = 0;
while (total < MAX_LENGTH) {
int count = is.read(buf, total, MAX_LENGTH - total);
if (count < 0) {
break;
}
total += count;
}
is.close();
String result = new String(buf, 0, total);
urlConn.disconnect();

Related

Android InputStream reads garbage ServerSocket running in a Thread. How should ServerSocket read from client socket?

I have a an application which communicates between two android devices through socket. It seems like they do connect, but when data from the client socket is read by ServerSocket (using InputStream), it doesnot return the desired result (it is supposed to return somrthing like "21.24891706//95.23659845//ff8iuj67898n47fu" ).Instead I'm getting " [B#416b9488" as the message.
My client runs an AsyncTask and server runs a Thread.
Can you please help me solve this problem? Any help will is appreciated. Thanks in advance.
Here is Server.java which runs on the server:
import android.content.Context;
import android.widget.Toast;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Enumeration;
public class Server {
Context context;
ServerSocket serverSocket;
String message = "";
static final int socketServerPORT = 8080;
ShowConnectedStudents activity;
public Server(ShowConnectedStudents callingActivity) {
activity = callingActivity;
Thread socketServerThread = new Thread(new SocketServerThread());
socketServerThread.start();
}
public int getPort() {
return socketServerPORT;
}
public void onDestroy() {
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class SocketServerThread extends Thread {
int count = 0;
byte buffer[] = new byte[1024];
int bytesRead;
String message;
#Override
public void run() {
try {
// create ServerSocket using specified port
serverSocket=new ServerSocket();
serverSocket.setReuseAddress(true);
serverSocket.bind(new InetSocketAddress(socketServerPORT));
while (true) {
// block the call until connection is created and return
// Socket object
Socket socket = serverSocket.accept();
message = "";
InputStream input = socket.getInputStream();
BufferedInputStream br= new BufferedInputStream(input);
while ((bytesRead = br.read(buffer)) != -1 ) {
message += " " + buffer.toString();
}
message += socket.isConnected();
message+=":"+socket.isClosed();
input.close();
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
activity.status.setText("Message is: " + message);
}
});
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Here is Client.java which runs on the client:
import android.os.AsyncTask;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
String status = "";
double Lat,Long;
String deviceId;
Socket socket = null;
ConnectToDevice activity;
byte buffer[] = new byte[1024];
int bytesRead;
Client(String addr, int port,double latitude,double longitude,String deviceIdentification,ConnectToDevice callingActivity) {
dstAddress = addr;
dstPort = port;
Lat=latitude;
Long=longitude;
deviceId=deviceIdentification;
activity=callingActivity;
if(dstAddress.charAt(0)=='/'){
dstAddress=dstAddress.substring(1);
}
}
#Override
protected Void doInBackground(Void... arg0) {
while(socket==null){
try {
socket = new Socket(dstAddress, dstPort);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
OutputStream outputStream = socket.getOutputStream();
PrintStream printStream = new PrintStream(outputStream,true);
printStream.print(Lat + "//" + Long+"//"+deviceId);
printStream.flush();
} catch (UnknownHostException e) {
e.printStackTrace();
status = "UnknownHostException: " + e.toString();
} catch (IOException e) {
e.printStackTrace();
status = "IOException: " + e.toString();
} finally {
}
return null;
}
#Override
protected void onPostExecute(Void result) {
activity.statusText.setText(Lat+ "//" + Long+"//"+deviceId);
super.onPostExecute(result);
}
}
toString() on a byte[] is not what you want, you're getting basically the memory address of the byte array
instead convert to a string, something like this
while ((bytesRead = br.read(buffer)) != -1 ) {
message += " " + new String(buffer, 0, bytesRead);
}
I have figured out another way, before reading this accepted answer. I'm posting it in case if it benefit anyone.
My data is text-only. So I wrapped the socket's input stream inside a Scanner.
InputStream input = socket.getInputStream();
Scanner scanner= new Scanner(input);
while(scanner.hasNextLine()){
message+=scanner.nextLine();
}

How to resolve android.os.networkonmainthreadexception

I am new to android and I am trying to read data from a server. I use a util and call that util like this
private void ParseSource(String Url){
String source = new Cls_SourceGrabber().grabSource(Url);
}
But I am getting a android.os.networkonmainthreadexception. How can I reduce that?
My SourceGrabber util:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
public class Cls_SourceGrabber {
private HttpGet mRequest;
private HttpClient mClient;
private BufferedReader mReader;
private StringBuffer mBuffer;
private String mNewLine;
public Cls_SourceGrabber() {
mRequest = new HttpGet();
InitializeClient();
mReader = null;
mBuffer = new StringBuffer(10000);
mNewLine = System.getProperty("line.separator");
}
private void InitializeClient() {
if (mClient == null || mClient.getConnectionManager() == null) {
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 4500);
HttpConnectionParams.setSoTimeout(httpParameters, 10000);
// HttpConnectionParams.setTcpNoDelay(httpParameters, true);
mClient = new DefaultHttpClient(httpParameters);
}
}
/*
*Grab the full source
*/
public String grabSource(String url) {
mBuffer.setLength(0);
InitializeClient();
String source = "";
try {
mRequest.setURI(new URI(url));
HttpResponse response = mClient.execute(mRequest);
mReader = new BufferedReader(new InputStreamReader(response
.getEntity().getContent()));
String line = "";
while ((line = mReader.readLine()) != null) {
mBuffer.append(line);
mBuffer.append(mNewLine);
source = mBuffer.toString();
if (Thread.interrupted()) {
break;
}
}
} catch (ConnectTimeoutException e) {
source = "Connection Timed Out.";
} catch (java.net.UnknownHostException e) {
source = "No Internet Connection available!";
} catch (java.lang.ArrayIndexOutOfBoundsException e) {
source = "Site Parsing Exception.";
} catch (ClientProtocolException e) {
source = "Protocol Exception.";
} catch (IOException e) {
source = "Server not responding.";
} catch (URISyntaxException e) {
source = "Wrong URL!";
} catch (Exception e) {
source = "Exception - " + e.toString() + " - "
+ e.getMessage();
e.printStackTrace();
} finally {
closeReader();
}
return source;
}
}
First of all, I would not recommend on using HTTPClient any more, since it is not supported any more from sdk version 23.
So, it will be better to migrate the network operations to URL Connection.
Now, android never allows network operations on Main thread since it will block the UI thread for a considerable time, hence may cause crash or bad user experience.
You can take a look on these docs : Doc 1
The better way to do Network operations is by creating an AsyncTask.
Just take care not to access any UI thread element in the doInBackground method. You can modify UI Thread elements on onPreExecute or onPostExecute Methods.
I have created a NetworkOps Util. You can take a look on that, whether it may be any use for you :
import android.content.Context;
import android.net.Uri;
import android.util.Log;
import com.csehelper.variables.Constants;
import com.csehelper.variables.Keys;
import com.csehelper.variables.Url;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.ArrayList;
public class NetworkOps {
public final String EXCEPTION = "~Exception~";
/****************************
* Method to Grab Source
****************************/
public static String GrabSource(String URL) {
return PostData(URL, null);
}
/**
* *****************************************
* Method to Grab Source code from URL
* Posting Data
* *****************************************
*/
private static String PostData(String url, Uri.Builder uribuilder) {
String Source;
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection urlConnection = null;
try {
urlConnection = (HttpURLConnection) new URL(url).openConnection();
urlConnection.setDoOutput(true);
urlConnection.setConnectTimeout(10000);
if(uribuilder != null) {
String query = uribuilder.build().getEncodedQuery();
OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
}
urlConnection.connect();
if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
String line;
StringBuilder builder = new StringBuilder();
InputStreamReader isr = new InputStreamReader(
urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
while ((line = reader.readLine()) != null) {
builder.append(line);
}
Source = builder.toString();
} else {
Source = EXCEPTION + "Server unreachable. Check network connection.";
}
} catch (SocketTimeoutException e) {
Source = EXCEPTION + "Connection timed out.";
} catch (java.net.UnknownHostException e) {
Source = EXCEPTION + Constants.EXCEPTION_NO_NET;
} catch (ArrayIndexOutOfBoundsException e) {
Source = EXCEPTION + "Server error";
} catch (ProtocolException e) {
Source = EXCEPTION + "Protocol error";
} catch (IOException e) {
Source = EXCEPTION + "Server unreachable. Check network connection.";
} catch (Exception e) {
Source = EXCEPTION + "Error:" + e.toString() + " - "
+ e.getMessage();
e.printStackTrace();
} finally {
if (urlConnection != null) urlConnection.disconnect();
}
return Source;
}
}
Call these Static Functions from AsyncTask:
/*********************************
* AsyncTask to GrabSource
********************************/
class AsyncTask_GrabSource extends AsyncTask<Void, Void, Void> {
String Source = null;
String url = "https://enigmatic-woodland-35608.herokuapp.com/pager.json";
#Override
protected void onPreExecute() {
//Runs on Main Thread. You can access your UI elements here.
}
#Override
protected Void doInBackground(Void... params) {
// Don't access any UI elements from this function
Source = NetworkOps.GrabSource(this.url);
return null;
}
#Override
protected void onPostExecute(Void result) {
if (Source != null) {
if (!Source.contains("~Exception~")) {
//Show Error Message or do whatever you want
} else {
//Do Whatever with your Grabbed Sourcecode.
// This function runs on UI Thread, so you can update UI elements here
}
}
}
You can also post data with the function PostData. In method doInBackground, add this:
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("key", "value")
.appendQueryParameter("key2", "value2");
Source = NetworkOps.PostData(getApplicationContext(), url, builder);

android socket jelly bean

i want to ask some question for android socket. I create a sample app to send data to wifly module. But when i receive data from module i get socket timeout exception. Without setSoTimeout app freeze to inputStream.read. Here is my code:
package com.socket.wiflysocket;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
protected static final String TAG = "WIflySocket";
EditText textOut;
TextView textIn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textOut = (EditText)findViewById(R.id.textout);
Button buttonSend = (Button)findViewById(R.id.send);
textIn = (TextView)findViewById(R.id.textin);
buttonSend.setOnClickListener(buttonSendOnClickListener);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
Button.OnClickListener buttonSendOnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo == null || networkInfo.isConnected() == false) {
try {
throw new Exception("Network is not connected");
} catch (Exception e) {
e.printStackTrace();
}
}
else {
new SocketThread(textOut.getText().toString()).execute();
textOut.setText("");
}
}};
}
and asynkTask:
package com.socket.wiflysocket;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.os.AsyncTask;
import android.util.Log;
public class SocketThread extends AsyncTask<String, Void, String>{
private static final String TAG = "SocketAsyncTask";
private static final int BUFFER_SIZE = 8;
private String textViewIn;
private String output;
private Socket socket = null;
private PrintWriter outputStream;
private InputStreamReader inputStream;
public SocketThread(String paramTextViewIn)
{
this.textViewIn = paramTextViewIn;
}
#Override
protected String doInBackground(String ...views) {
Log.d(TAG, "Execute");
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
socket = new Socket("1.2.3.4", 2000);
socket.setSoTimeout(2000);
outputStream = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
inputStream = new InputStreamReader(socket.getInputStream());
if(socket.isConnected()) {
this.sendDataWithString(textViewIn);
output = this.receiveDataFromServer();
}
this.closeSocket();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally{
if (socket != null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataOutputStream != null){
try {
dataOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataInputStream != null){
try {
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return output;
}
/*
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
return textViewOut;
}
*/
private void closeSocket() {
if (socket != null) {
if (socket.isConnected()) {
try {
inputStream.close();
outputStream.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private void sendDataWithString(String message) {
if (message != null) {
outputStream.write(message);
outputStream.flush();
}
}
private String receiveDataFromServer() {
String message = "";
try {
int charsRead = 0;
char[] buffer = new char[BUFFER_SIZE];
while ((charsRead = inputStream.read(buffer)) != -1) {
message += new String(buffer).substring(0, charsRead);
}
closeSocket();
return message;
} catch (IOException e) {
//TODO work around
return message;
//return "Error receiving response: " + e.getMessage();
}
}
}
Permission that I add are :
android.permission.INTERNET;
android.permission.ACCESS_NETWORK_STATE
Can you suggest me, what is wrong, and how to fix this issue.
Thanks
Try this -
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("echo: " + in.readLine());
}
or this -
Reader r = new InputStreamReader(conn.getInputStream());
String line;
StringBuilder sb = new StringBuilder();
char[] chars = new char[4*1024];
int len;
while((len = r.read(chars))>=0) {
sb.append(chars, 0, len);
}
or this one -
byte[] resultBuff = new byte[0];
byte[] buff = new byte[1024];
int k = -1;
while((k = sock.getInputStream().read(buff, 0, buff.length)) > -1) {
byte[] tbuff = new byte[resultBuff.length + k];
System.arraycopy(resultBuff, 0, tbuff, 0, resultBuff.length); bytes
System.arraycopy(buff, 0, tbuff, resultBuff.length, k);
resultBuff = tbuff;
}
SocketFactory creates socket for you
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import javax.net.SocketFactory;
...
private Socket socket = null;
public Reader reader = null;
public Writer writer = null;
protected void init(String host, int port) throws ClientException {
try {
socket = SocketFactory.getDefault().createSocket(host, port);
} catch (UnknownHostException e) {
throw new ClientException(e);
} catch (IOException e) {
throw new ClientException(e);
}
initDataManagers();
}
protected void initDataManagers() throws ClientException {
try {
reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new ClientException(e);
} catch (IOException e) {
throw new ClientException(e);
}
}

sending data to server from text file using a service

I am sending data from text file to server using service code given below. It sends data line by line to server. I want the service to run in background continuously.For this I have written asyncTask. But it sends all data once and then stops.
public class BackgroundService extends Service
{
private static final String TAG = "BackgroundService";
String line=null;
Context mContext = null;
File file;RandomAccessFile in = null;
StringEntity se ;
HttpEntity entity=null;
final static int SERVICE_NAME = 1;
int WORK_TYPE;
public BackgroundService()
{
//super(TAG);
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),"in BackgroundService", Toast.LENGTH_LONG).show();
mContext = getBaseContext();
WORK_TYPE = 2;
new BackgroundTask(mContext).execute();
return super.onStartCommand(intent, flags, startId);
}
public class BackgroundTask extends AsyncTask<String, String, Void>
{
Context mContext = null;String response;
public BackgroundTask(Context context)
{
mContext = context;
}
protected void onPreExecute()
{
Toast.makeText(getApplicationContext(),"1", Toast.LENGTH_LONG).show();
}
protected Void doInBackground(final String... args)
{
switch (WORK_TYPE)
{
case 2:
File file = new File(Environment.getExternalStorageDirectory(),"/BPCLTracker/gpsdata.txt");
int i=0;
RandomAccessFile in = null;
try {
in = new RandomAccessFile(file, "rw");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
while ((line = in.readLine()) != null)
{
String input = line.toString();
response = sendDataToServer(input);
// JsonUtils.parseServerData(response, hashMapObj);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}//switch
return null;
}//doInBackground
protected void onPostExecute(final Void unused)
{
Toast.makeText(getApplicationContext(),"3", Toast.LENGTH_LONG).show();
switch (WORK_TYPE)
{
case 2:
if (!"".equalsIgnoreCase(response) && response != null)
{
//DeviceUtils.deviceRegistration(hashMapObj, mContext);
callService(1);
}
try {
if((line = in.readLine()) == null && entity!=null)
{
file.delete();
new BackgroundTask(mContext).execute();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
}
}
public void callService(int work)
{
WORK_TYPE = work;
new BackgroundTask(mContext).execute();
}
public String sendDataToServer(String data)
{
StringBuffer sb = new StringBuffer("");
String serverUrl = "http://67.23.166.35:80/android/insert.php" ;
try
{
URL url = new URL(serverUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setConnectTimeout(6 * 10 * 1000);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
conn.setRequestMethod("POST");
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = "";
while ((line = rd.readLine()) != null)
{
// Process line...
sb.append(line);
}
wr.close();
rd.close();
return sb.toString();
}
catch (Exception e)
{
Log.d("Exception : ", e.getStackTrace().toString());
}
return sb.toString();
}
}
Thank you
I have Modify your code:
Check my all code this ll give you idea about send line one by one. Please do rest of logic this way. i have also remove some method.
This is not all code but it ll give you IDEA.
package com.example.getjson;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.http.HttpEntity;
import org.apache.http.entity.StringEntity;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class backservice extends Service {
private static final String TAG = "BackgroundService";
String line = null;
Context mContext = null;
File file;
RandomAccessFile in = null;
StringEntity se;
HttpEntity entity = null;
final static int SERVICE_NAME = 1;
int WORK_TYPE;
String response;
String input = "";
public backservice() {
// super(TAG);
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "in BackgroundService",
Toast.LENGTH_LONG).show();
mContext = getBaseContext();
WORK_TYPE = 2;
// new BackgroundTask(mContext).execute();
switch (WORK_TYPE) {
case 2:
File file = new File(Environment.getExternalStorageDirectory(),
"/BPCLTracker/gpsdata.txt");
int i = 0;
RandomAccessFile in = null;
try {
in = new RandomAccessFile(file, "rw");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
while ((line = in.readLine()) != null) {
input = line.toString();
// response = sendDataToServer(input);
new BackgroundTask(mContext).execute();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
return super.onStartCommand(intent, flags, startId);
}
public class BackgroundTask extends AsyncTask<String, String, Void> {
Context mContext = null;
public BackgroundTask(Context context) {
mContext = context;
}
protected void onPreExecute() {
Toast.makeText(getApplicationContext(), "1", Toast.LENGTH_LONG)
.show();
}
protected Void doInBackground(final String... args) {
response = sendDataToServer(input);
return null;
}
protected void onPostExecute(final Void unused) {
}
}
public void callService(int work) {
WORK_TYPE = work;
new BackgroundTask(mContext).execute();
}
public String sendDataToServer(String data) {
StringBuffer sb = new StringBuffer("");
String serverUrl = "http://67.23.166.35:80/android/insert.php";
try {
URL url = new URL(serverUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setConnectTimeout(6 * 10 * 1000);
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
conn.setRequestMethod("POST");
OutputStreamWriter wr = new OutputStreamWriter(
conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String line = "";
while ((line = rd.readLine()) != null) {
// Process line...
sb.append(line);
}
wr.close();
rd.close();
return sb.toString();
} catch (Exception e) {
Log.d("Exception : ", e.getStackTrace().toString());
}
return sb.toString();
}
}

how to send audio file from android client to servlet server

I want to send an audio file .mp3 file from android client to servlet server and save it in a location. If I play that saved .mp3 file in that location it should play.
My question is there a way to send a .mp3 file directly from client to server and retrieve that mp3 file in servlet.
My client side code is as follows:
package com.android.audiorecord;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import org.apache.commons.io.FileUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import com.android.audiofileplayer.StreamingMp3Player;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
public class AudioRecordActivity extends Activity
{
private static final String LOG_TAG = "AudioRecordTest";
private static String mFileName = null;
private String url = "QRFileSaveServlet";
String result;
byte[] value;
String s;
byte[] filebyte,clientbyte;
String readString;
private RecordButton mRecordButton = null;
private MediaRecorder mRecorder = null;
private SubmitButton mSubmitButton = null;
private PlayButton mPlayButton = null;
private MediaPlayer mPlayer = null;
String fileresult = "";
HttpResponse response;
private void onRecord(boolean start) {
if (start) {
startRecording();
} else {
stopRecording();
}
}
private void onPlay(boolean start) {
if (start) {
startPlaying();
} else {
stopPlaying();
}
}
private void startPlaying() {
mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(mFileName);
mPlayer.prepare();
mPlayer.start();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
}
private void stopPlaying() {
mPlayer.release();
mPlayer = null;
}
private void startRecording() {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
mRecorder.setOutputFile(mFileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
mRecorder.prepare();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
mRecorder.start();
}
/* public boolean saveas(int ressound){
byte[] buffer=null;
InputStream fIn = getBaseContext().getResources().openRawResource(ressound);
int size=0;
try {
size = fIn.available();
buffer = new byte[size];
fIn.read(buffer);
fIn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
return false;
}
String path="/sdcard/media/audio/ringtones/";
String filename="examplefile"+".ogg";
boolean exists = (new File(path)).exists();
if (!exists){new File(path).mkdirs();}
FileOutputStream save;
try {
save = new FileOutputStream(path+filename);
save.write(buffer);
save.flush();
save.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
return false;
} catch (IOException e) {
// TODO Auto-generated catch block
return false;
}
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"+path+filename)));
File k = new File(path, filename);
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, "exampletitle");
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/ogg");
values.put(MediaStore.Audio.Media.ARTIST, "cssounds ");
values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
values.put(MediaStore.Audio.Media.IS_ALARM, true);
values.put(MediaStore.Audio.Media.IS_MUSIC, false);
//Insert it into the database
this.getContentResolver().insert(MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath()), values);
return true;
} */
private void stopRecording() {
mRecorder.stop();
mRecorder.release();
// mRecorder.reset();
mRecorder = null;
}
class RecordButton extends Button {
boolean mStartRecording = true;
OnClickListener clicker = new OnClickListener() {
public void onClick(View v) {
onRecord(mStartRecording);
if (mStartRecording) {
setText("Stop recording");
} else {
setText("Start recording");
}
mStartRecording = !mStartRecording;
}
};
public RecordButton(Context ctx) {
super(ctx);
setText("Start recording");
setOnClickListener(clicker);
}
}
class PlayButton extends Button {
boolean mStartPlaying = true;
OnClickListener clicker = new OnClickListener() {
public void onClick(View v) {
onPlay(mStartPlaying);
if (mStartPlaying) {
setText("Stop playing");
} else {
setText("Start playing");
}
mStartPlaying = !mStartPlaying;
}
};
public PlayButton(Context ctx) {
super(ctx);
setText("Start playing");
setOnClickListener(clicker);
}
}
class SubmitButton extends Button {
OnClickListener clicker = new OnClickListener() {
public void onClick(View v) {
File f = new File(Environment.getExternalStorageDirectory()+"/audiorecordtest.mp3");
//
//byte[] file = fileresult.getBytes();
try {
filebyte = FileUtils.readFileToByteArray(f);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("$$$$$$$$$$$" + filebyte);
clientbyte = Base64.encode(filebyte, MODE_APPEND);//(filebyte, MODE_APPEND);
s= new String(clientbyte);
System.out.println("**************" + s);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("Audiofile", s));
result = AudioServer.executePost(url, nameValuePairs);
result = result.trim();
System.out.println("response recieved " + result);
if(result!=null){
Bundle bundle = new Bundle();
Intent explicitIntent = new Intent(AudioRecordActivity.this,
StreamingMp3Player.class);
bundle.putString("result", result);
explicitIntent.putExtras(bundle);
startActivity(explicitIntent);
}
}
};
public SubmitButton(Context ctx) {
super(ctx);
setText("Save");
setOnClickListener(clicker);
}
}
public AudioRecordActivity() {
mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
mFileName += "/audiorecordtest.mp3";
}
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
LinearLayout ll = new LinearLayout(this);
mRecordButton = new RecordButton(this);
ll.addView(mRecordButton,
new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
0));
mPlayButton = new PlayButton(this);
ll.addView(mPlayButton,
new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
0));
mSubmitButton = new SubmitButton(this);
ll.addView(mSubmitButton, new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT, 0));
setContentView(ll);
}
#Override
public void onPause() {
super.onPause();
if (mRecorder != null) {
mRecorder.release();
mRecorder = null;
}
if (mPlayer != null) {
mPlayer.release();
mPlayer = null;
}
}
}
in this can i send audiorecordtest.mp3 file direcly to server without encoding to byte[] and send it in namevalue pair.
My server side code is as follows:
package com.gsr.qrbarcode;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import com.android.gsr.utils.AudioSampleReader;
import com.android.gsr.utils.AudioSampleWriter;
import com.android.gsr.utils.Base64;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
//import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFileFormat.Type;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;
import org.apache.commons.io.FileUtils;
/**
* Servlet implementation class QRFileSaveServlet
*/
//#WebServlet("/QRFileSaveServlet")
public class QRFileSaveServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
AudioInputStream ais;
/**
* Default constructor.
*/
public QRFileSaveServlet() {
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String qrfile= request.getParameter("Audiofile");
System.out.println("String Parameter \"" +qrfile );
byte[] audiofile=Base64.decode(qrfile);
String newStr = new String(audiofile);
// Display the contents of the byte array.
System.out.println("The new String equals \"" +newStr + "\"");
String filePath = this.getServletContext().getRealPath("/")+"";
System.out.println("Path of the file " + filePath);
String fileupload="AudioFileStorage";
//PrintWriter out = response.getWriter();
File f;
f= new File(filePath);
//int status = 0;
if(f.exists()) {
filePath += fileupload;
f = new File(filePath);
if(!f.exists()){
f.mkdir();
}
f = new File(filePath,"test.mp3");
if(!f.exists()) {
FileOutputStream fos = new FileOutputStream(f);
fos.write(audiofile);
fos.flush();
fos.close();
} else {
//out.println("failure");
ServletOutputStream stream = null;
BufferedInputStream buf = null;
try{
stream = response.getOutputStream();
// File mp3 = new File(mp3Dir + "/" + fileName);
response.setContentType("audio/mpeg");
response.addHeader("Content-Disposition","attachment; filename="+f );
response.setContentLength( (int) f.length() );
FileInputStream input = new FileInputStream(f);
buf = new BufferedInputStream(input);
int readBytes = 0;
while((readBytes = buf.read()) != -1)
stream.write(readBytes);
System.out.println("Response Stream"+stream);
} catch (IOException ioe){
throw new ServletException(ioe.getMessage());
} finally {
if(stream != null)
stream.close();
if(buf != null)
buf.close();
}
}
}
if (filePath == null || filePath.equals(""))
throw new ServletException(
"Invalid or non-existent mp3Dir context-param.");
URL url = null;
try{
url = f.toURL();
System.out.println("URL : "+ url);
System.out.println("Converting process Successfully");
}
catch (MalformedURLException me){
System.out.println("Converting process error");
}
//String rfilepath=this.getServletContext().getRealPath("/")+" AudioFileStorage/test.mp3";
//System.out.println("Path of the rfilepath " + rfilepath);
}
}
here can i get that audiorecordtest.mp3 file directly from client without decoding in server side and play it in this servlet
my server connection in local for client
executepost() is as follows:
package com.android.audio;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
public class AudioServer {
static InputStream is;
private static String API_URL = "http://192.168.15.71:8088/QRBarCodeServer/";
public static String executePost(String apiurl,
ArrayList<NameValuePair> urlParameters) {
try {
// Create connection
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(API_URL + apiurl);
httppost.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
// Get Response
// InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response1 = new StringBuffer();
while ((line = rd.readLine()) != null) {
response1.append(line);
response1.append('\r');
}
rd.close();
return response1.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static String executeHttpGet(String apiurl) throws Exception {
BufferedReader in = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(API_URL + apiurl);
request.setURI(new URI(apiurl));
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
here is simple way to do that
1: from android side read that .mp3 file and create base64String from it.
2: At servier side read this base64String and convert it back to .mp3 file.
to convert any file to base64String following is the process
File file = new File(Environment.getExternalStorageDirectory() + "/hello-4.wav");
byte[] bytes = FileUtils.readFileToByteArray(file);
String encoded = Base64.encodeToString(bytes, 0);
You can reach it using apache MultipartEntity:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(BASE_URL);
MultipartEntity mpEntity = new MultipartEntity();
mpEntity.addPart("Audiofile", new FileBody(file, "audio/mpeg"));
post.setEntity(mpEntity);
HttpResponse res = client.execute(post);
Yea you can send this in Servlet there is Mime type mime means multimedia extension
I am sending code i can guarantee that it will work in Servlet in java and you should take
care for android by own
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SendMp3Envious extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String fileName = (String) request.getParameter("file");
if (fileName == null || fileName.equals(""))
throw new ServletException(
"Invalid or non-existent file parameter in SendMp3 servlet.");
if (fileName.indexOf(".mp3") == -1)
fileName = fileName + ".mp3";
String mp3Dir = getServletContext().getInitParameter("mp3-dir");
if (mp3Dir == null || mp3Dir.equals(""))
throw new ServletException(
"Invalid or non-existent mp3Dir context-param.");
ServletOutputStream stream = null;
BufferedInputStream buf = null;
try {
stream = response.getOutputStream();
File mp3 = new File(mp3Dir + "/" + fileName);
//set response headers
response.setContentType("audio/mpeg");
response.addHeader("Content-Disposition", "attachment; filename="
+ fileName);
response.setContentLength((int) mp3.length());
FileInputStream input = new FileInputStream(mp3);
buf = new BufferedInputStream(input);
int readBytes = 0;
//read from the file; write to the ServletOutputStream
while ((readBytes = buf.read()) != -1)
stream.write(readBytes);
} catch (IOException ioe) {
throw new ServletException(ioe.getMessage());
} finally {
if (stream != null)
stream.close();
if (buf != null)
buf.close();
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}

Categories

Resources