-1

My requirement is to upload the images to server using a Multipart request. I was able to create a Multipart Http Request using the HttpClient, which is deprecated. Is it possible to achieve the same using HttpUrlConnection? If yes, how?

Update:

Current code

{
    ProgressDialog progress_dialog;

    @Override
        protected void onPreExecute() {
        // setting progress bar to zero
        progress_dialog=new ProgressDialog(CreateAlbum.this);
        progress_dialog.setTitle("Loading..");
        progress_dialog.show();

        super.onPreExecute();
    }

    @Override
        protected String doInBackground(Void... params) {
            return uploadFile();
    }

    @SuppressWarnings("deprecation")
    private String uploadFile() {
        String responseString = null;

        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://192.168.1.42:8080/test/fileUpload.php");

        try
        {
            MultipartEntityBuilder entity = MultipartEntityBuilder.create();        
            entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

            File sourceFile = new File(fileUri);

            // Adding file data to http body
            entity.addPart("image", new FileBody(sourceFile));

            // Extra parameters if you want to pass to server
            entity.addPart("website",
                            new StringBody("www.androidhive.info"));
            entity.addPart("email", new StringBody("abc@gmail.com"));

            httppost.setEntity(entity);

            // Making server call
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity r_entity = response.getEntity();

            int statusCode = response.getStatusLine().getStatusCode();
            Log.i("RAE", "STATUS CODE IS"+statusCode);
            if (statusCode == 200) {
                // Server response
                responseString = EntityUtils.toString(r_entity);
            } else {
                responseString = "Error occurred! Http Status Code: "
                                + statusCode;
            }

        } catch (ClientProtocolException e) {
                responseString = e.toString();
        } catch (IOException e) {
                responseString = e.toString();
        }
        return responseString;

    }

    @Override
    protected void onPostExecute(String result) {
        Log.e("RAE", "Response from server: " + result);
        progress_dialog.dismiss();
        // showing the server response in an alert dialog
        Toast.makeText(getApplicationContext(), "File Uploaded", Toast.LENGTH_SHORT).show();

        super.onPostExecute(result);
    }

}
Vladimir Markeev
  • 654
  • 10
  • 25
Rahul Batra
  • 123
  • 1
  • 2
  • 10

4 Answers4

0

AndroidHttpClient has been depreciated and has no longer support from the developers. So one will have to use java's own HttpURLConnection under java.net package. Here is a demo android application which implements HttpURLConnection. Just use the following git commands and run the application in android studio

Clone the git project :-

git clone https://github.com/viper-pranish/android-tutorial.git

Download the right version of project where HttpURLConnection is implemented

git checkout 399e3d1f9624353e522faf350f38a12db635c09a
viper
  • 1,836
  • 4
  • 25
  • 41
-1

EDIT

After you understand from my code how to make a POST with HttpUrlConnection, you can edit it and integrate the following answers: Sending files using POST with HttpURLConnection


This is how I make a form-encoded POST:

// Connection
URL url = new URL("http://www.example.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setDoOutput(true);
conn.setDoInput(true);

// Data to be sent
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.writeBytes(printParams(params));
out.flush();
out.close();

// Print received response
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
    System.out.println(inputLine);
}
in.close();

where printParams is a simple function to trasform a Map into a string like a=b&c=d:

public static String printParams(Map<String, String> params) {
    StringBuffer sb = new StringBuffer();
    for (Map.Entry<String, String> e: params.entrySet()) {
        if (sb.length() > 0) {
            sb.append("&");
        }
        sb.append(e.getKey()).append('=').append(e.getValue());
    }
    return sb.toString();
}
vault
  • 3,930
  • 1
  • 35
  • 46
-1

This link has everything you need to send a file to server using multipart. It has been updated to use the most recent http classes in android. I have tested it and use it myself today. Cheers!

http://www.androidhive.info/2014/12/android-uploading-camera-image-video-to-server-with-progress-bar/

Steve C.
  • 1,333
  • 3
  • 19
  • 50
  • I think you did not read the question detail. This example has deprecated classes.I want to avoid depecrate code. @Steve – Rahul Batra May 05 '15 at 10:19
-1

For the nexts post show your code, the programmers need see that for give more great help, thanks. On the one hand I always use in my apps httpClient and it's the best way for me because you can configuration a specific client with handling cookies, authentication, connection management, and other features, it's simple if you have the code. If you want to see more info from this theme you can visit this links, in Class Overview part:

http://developer.android.com/reference/org/apache/http/client/HttpClient.html http://developer.android.com/reference/java/net/HttpURLConnection.html

On the other hand, if you want to do a multiple connections with your server I recommend a parallel programming with httpClient with processes and threads can read more info here: http://developer.android.com/guide/components/processes-and-threads.html


// Last Update //

Sorry Rahul Batra I work with API 21... I noted this for next version of my app. But as the first Step I will try to use a backgroud tasks with httpURLConnection. This post have a really great information:

http://android-developers.blogspot.com.es/2011/09/androids-http-clients.html


I hope it help you this answer!! If you need more information or anything let me know, good luck Rahul Batra.