Monthly Archives: March 2014

Uploading Image from Android App to Server ~ Programmatically :)


Its been such a long time ever since I have posted anything into the blog. Well not posting into it does not mean I have not learned anything new in the mean time. Well, I have learned so many different things in this month that I really have not been able to keep track of it. But, I will eventually post about all of them. Today, I am posting about the way we perform image uploading from android app to server. 

I thought uploading image to server was really hard. I researched for whole day. Different blogs were giving different types of suggestions. I was literally going through paralysis analysis. Then,after a day I finally uploaded image to the server. So, I am feeling great and happy right now.

To perform uploading, you will have to first understand the following things:

HTTP is a protocol for exchanging messages between a client and a server. An HTTP client opens a connection and sends a request message to an HTTP server; the server then returns a response message, usually containing the resource that was requested. After delivering the response, the server closes the connection. Request has three parts : a method name – GET or POST method , resources and the version of HTTP being used. Response also has three parts: the HTTP version, a response status code that gives the result of the request, and status code.

GET method : Requests data from a specified resource.

Query strings (name/value pairs) is send in the URL of a GET request. It should only be used to retrieve data

POST method : Submits data to be processed to a specified resource

Query strings (name/value pairs) is sent in the HTTP message body of a POST request.

Requests made through these methods return an instance of HTTPResponse. This instance of HTTPResponse has methods for accessing the response headers ( getHeader()), response info (getStatusCode()), response data (getData(), getInputStream()) and any trailers that might have been sent.

Although the java.net packages provides basic functionality for accessing resources via HTTP, it doesn’t provide the full flexibility or functionality needed by many applications.

So we need following jar file which can be downloaded from here to get an efficient, up-to-date, and feature-rich package implementing the client side of the most recent HTTP standards and recommendations-

  • httpcore-4.3.2.jar
  • httpmime-4.3.1.jar

Hence, we have understood how Client-Server communication is handled. Now through the following code snippet, we can upload image to the server:

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

		@Override
		protected String doInBackground(Void... params) {
			// TODO Auto-generated method stub
			String result = "";

			// Client-side HTTP transport library
			HttpClient httpClient = new DefaultHttpClient();

			// using POST method
			HttpPost httpPostRequest = new HttpPost(imagePostUrl);
			try {

				// creating a file body consisting of the file that we want to
				// send to the server
				FileBody bin = new FileBody(imageFile);

				/**
				 * An HTTP entity is the majority of an HTTP request or
				 * response, consisting of some of the headers and the body, if
				 * present. It seems to be the entire request or response
				 * without the request or status line (although only certain
				 * header fields are considered part of the entity).
				 * 
				 * */
				MultipartEntityBuilder multiPartEntityBuilder = MultipartEntityBuilder.create();
				multiPartEntityBuilder.addPart("images[1]", bin);
				httpPostRequest.setEntity(multiPartEntityBuilder.build());

				// Execute POST request to the given URL
				HttpResponse httpResponse = null;
				httpResponse = httpClient.execute(httpPostRequest);

				// receive response as inputStream
				InputStream inputStream = null;
				inputStream = httpResponse.getEntity().getContent();

				if (inputStream != null)
					result = convertInputStreamToString(inputStream);
				else
					result = "Did not work!";
				return result;
			} catch (Exception e) {

				return null;
			}

			// return result;
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			uploadStatus.setText("Uploading image to server");
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			uploadStatus.setText(result);
		}

	}

	private static String convertInputStreamToString(InputStream inputStream)
			throws IOException {
		BufferedReader bufferedReader = new BufferedReader(
				new InputStreamReader(inputStream));
		String line = "";
		String result = "";
		while ((line = bufferedReader.readLine()) != null)
			result += line;

		inputStream.close();
		return result;

	}

References:

http://www.jmarshall.com/easy/http/

http://www.innovation.ch/java/HTTPClient/getting_started.html

http://hc.apache.org/downloads.cgi

http://stackoverflow.com/questions/20284542/upload-photo-using-httppost-multipartentitybuilder

http://stackoverflow.com/questions/18964288/upload-a-file-through-an-http-form-via-multipartentitybuilder-with-a-progress

Advertisements