Question

I have created a small application which sends an audio file from android to servlet but i am getting a connection error. Following is my full code. Please review it.

Client code

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {

    private static final int SELECT_AUDIO = 2;
    String selectedPath = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        openGalleryAudio();
    }
/*
    @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;
    }
*/
    public void openGalleryAudio(){

        Intent intent = new Intent();
            intent.setType("audio/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent,"Select Audio "), SELECT_AUDIO);
       }

        public void onActivityResult(int requestCode, int resultCode, Intent data) {

            if (resultCode == RESULT_OK) {

                if (requestCode == SELECT_AUDIO)
                {
                    System.out.println("SELECT_AUDIO");
                    Uri selectedImageUri = data.getData();
                    selectedPath = getPath(selectedImageUri);
                    System.out.println("SELECT_AUDIO Path : " + selectedPath);
                    new FileTrans().execute("");
                }

            }
        }

        public String getPath(Uri uri) {
            String[] projection = { MediaStore.Images.Media.DATA };
            Cursor cursor = managedQuery(uri, projection, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } 

    private class FileTrans extends AsyncTask<String, Void, String>
    {

    @Override
    protected String doInBackground(String... arg0) {

         HttpURLConnection conn = null;
         DataOutputStream dos = null;
         DataInputStream inStream = null;
         String lineEnd = "\r\n";
         String twoHyphens = "--";
         String boundary =  "*****";
         int bytesRead, bytesAvailable, bufferSize;
         byte[] buffer;
         int maxBufferSize = 4*1024*1024;
         String responseFromServer = "";
         String urlString = "http://10.0.2.2:8080/FileUpload/FUServlet";
         try
         {

         FileInputStream fileInputStream = new FileInputStream(new File(selectedPath) );
          // open a URL connection to the Servlet
          URL url = new URL(urlString);
          // Open a HTTP connection to the URL
          conn = (HttpURLConnection) url.openConnection();
          conn.setConnectTimeout(7000);
          // Allow Inputs
          conn.setDoInput(true);
          // Allow Outputs
          conn.setDoOutput(true);
          // Don't use a cached copy.
          conn.setUseCaches(false);
          // Use a post method.
          conn.setRequestMethod("POST");
          conn.setRequestProperty("Connection", "Keep-Alive");
          conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
          dos = new DataOutputStream( conn.getOutputStream() );
          dos.writeBytes(twoHyphens + boundary + lineEnd);
          dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + selectedPath + "\"" + lineEnd);
          dos.writeBytes(lineEnd);
          // create a buffer of maximum size
          bytesAvailable = fileInputStream.available();
          bufferSize = Math.min(bytesAvailable, maxBufferSize);
          buffer = new byte[bufferSize];
          // read file and write it into form...
          bytesRead = fileInputStream.read(buffer, 0, bufferSize);
          while (bytesRead > 0)
          {
           dos.write(buffer, 0, bufferSize);
           bytesAvailable = fileInputStream.available();
           bufferSize = Math.min(bytesAvailable, maxBufferSize);
           bytesRead = fileInputStream.read(buffer, 0, bufferSize);
          }
          // send multipart form data necesssary after file data...
          dos.writeBytes(lineEnd);
          dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
          // close streams
          Log.e("Debug","File is written");
          fileInputStream.close();
          dos.flush();
          dos.close();
         }
         catch (MalformedURLException ex)
         {
              Log.e("Debug", "error: " + ex.getMessage(), ex);
         }
         catch (IOException ioe)
         {
              Log.e("Debug", "error: " + ioe.getMessage(), ioe);
         }
         //------------------ read the SERVER RESPONSE
         try {
               inStream = new DataInputStream ( conn.getInputStream() );
               String str;

               while (( str = inStream.readLine()) != null)
               {
                    Log.e("Debug","Server Response "+str);
               }
               inStream.close();

         }
         catch (IOException ioex){
              Log.e("Debug", "error: " + ioex.getMessage(), ioex);
         }

        return null;
    }
    @Override
    protected void onPostExecute(String result) { 

    }

    @Override
    protected void onPreExecute() {
    }

    @Override
    protected void onProgressUpdate(Void... values) {
    }

    }

}

here is my servlet code

public class FUServlet extends HttpServlet {
 private boolean isMultipart;
       private String filePath;
       private int maxFileSize = 9000 * 1024;
       private int maxMemSize = 6 * 1024;
       private File file ;

       public void init( ){
          // Get the file location where it would be stored.
          filePath =
                 getServletContext().getInitParameter("file-upload");
       }
       public void doPost(HttpServletRequest request,
                   HttpServletResponse response)
                  throws ServletException, java.io.IOException {
          // Check that we have a file upload request
          isMultipart = ServletFileUpload.isMultipartContent(request);
          response.setContentType("text/html");
          java.io.PrintWriter out = response.getWriter( );
          if( !isMultipart ){
             out.println("<html>");
             out.println("<head>");
             out.println("<title>Servlet upload</title>");
             out.println("</head>");
             out.println("<body>");
             out.println("<p>No file uploaded</p>");
             out.println("</body>");
             out.println("</html>");
             return;
          }
          DiskFileItemFactory factory = new DiskFileItemFactory();
      // maximum size that will be stored in memory
      factory.setSizeThreshold(maxMemSize);
      // Location to save data that is larger than maxMemSize.
      factory.setRepository(new File("D:\\temp"));

      // Create a new file upload handler
      ServletFileUpload upload = new ServletFileUpload(factory);
      // maximum file size to be uploaded.
      upload.setSizeMax( maxFileSize );

      try{
      // Parse the request to get file items.
      List fileItems = upload.parseRequest(request);

      // Process the uploaded file items
      Iterator i = fileItems.iterator();

      out.println("<html>");
      out.println("<head>");
      out.println("<title>Servlet upload</title>");
      out.println("</head>");
      out.println("<body>");
      while ( i.hasNext () )
      {
         FileItem fi = (FileItem)i.next();
         if ( !fi.isFormField () )
         {
            // Get the uploaded file parameters
            String fieldName = fi.getFieldName();
            String fileName = fi.getName();
            String contentType = fi.getContentType();
            boolean isInMemory = fi.isInMemory();
            long sizeInBytes = fi.getSize();
            // Write the file
            if( fileName.lastIndexOf("\\") >= 0 ){
               file = new File( filePath +
               fileName.substring( fileName.lastIndexOf("\\"))) ;
            }else{
               file = new File( filePath +
               fileName.substring(fileName.lastIndexOf("\\")+1)) ;
            }
            fi.write( file ) ;
            out.println("Uploaded Filename: " + fileName + "<br>");
         }
      }
      out.println("</body>");
      out.println("</html>");
   }catch(Exception ex) {
       System.out.println(ex);
   }
   }
   public void doGet(HttpServletRequest request,
                       HttpServletResponse response)
        throws ServletException, java.io.IOException {

        throw new ServletException("GET method used with " +
                getClass( ).getName( )+": POST method required.");
   }
}

and i have included all the necessary permission in my manifest file

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

Still I am getting error Can anyone please help me out.

here is my logcat

01-28 17:10:45.627: E/Debug(30428): error: failed to connect to /10.0.2.2 (port 8080) after 7000ms
01-28 17:10:45.627: E/Debug(30428): java.net.SocketTimeoutException: failed to connect to /10.0.2.2 (port 8080) after 7000ms
01-28 17:10:45.627: E/Debug(30428):     at libcore.io.IoBridge.connectErrno(IoBridge.java:176)
01-28 17:10:45.627: E/Debug(30428):     at libcore.io.IoBridge.connect(IoBridge.java:112)
01-28 17:10:45.627: E/Debug(30428):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
01-28 17:10:45.627: E/Debug(30428):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
01-28 17:10:45.627: E/Debug(30428):     at java.net.Socket.connect(Socket.java:857)
01-28 17:10:45.627: E/Debug(30428):     at libcore.net.http.HttpConnection.<init>(HttpConnection.java:76)
01-28 17:10:45.627: E/Debug(30428):     at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
01-28 17:10:45.627: E/Debug(30428):     at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340)
01-28 17:10:45.627: E/Debug(30428):     at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
01-28 17:10:45.627: E/Debug(30428):     at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
01-28 17:10:45.627: E/Debug(30428):     at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:316)
01-28 17:10:45.627: E/Debug(30428):     at libcore.net.http.HttpEngine.connect(HttpEngine.java:311)
01-28 17:10:45.627: E/Debug(30428):     at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:290)
01-28 17:10:45.627: E/Debug(30428):     at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:240)
01-28 17:10:45.627: E/Debug(30428):     at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:81)
01-28 17:10:45.627: E/Debug(30428):     at libcore.net.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:205)
01-28 17:10:45.627: E/Debug(30428):     at com.android.fileupload.MainActivity$FileTrans.doInBackground(MainActivity.java:110)
Was it helpful?

Solution

Actually the problem was with the urlString. I have not put the servlet code on server and i was trying to run the app on my phone. that is why I was getting the connection error.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top