Thursday 9 June 2016

File Upload using Spring RestFul service

File Upload using Spring RestFul service

In this blow we will try to upload file file using Spring RestFul service.

First we need to register a bean in spring configuration XMl file for MultipartResolver that Spring support for uploading.
Here we have used CommonsMultipartResolver provided by spring framework to upload a file

Example:
<bean id="multipartResolver"              class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
p:defaultEncoding="utf-8"/>

Now create a controller and annotating with proper path.
Example:
@RequestMapping(value = "/image/ imageid/{imageid}", method = RequestMethod.POST)
  public String imageUpload(HttpServletRequest request,
      @RequestParam("imagefile") MultipartFile file) throws IOException {    
    InputStream stream = file.getInputStream();
            String fileName = file.getOriginalFilename();          
            System.out.println(“File name: “ + fileName);
            /*
            Now you have InputStream, file name and other information available so, you can save where you want
            */
    return "SUCCESS";
  }


To the created service we can test it using Postmaster app plugin of Chrome.


Consuming Web service in Java

Consume Web service using HttpURLConnection
We can call Web services method in java using classes URL and HttpURLConnection.
And can be used with Android to consume web services 
URL: Class URL represents a Uniform Resource Locator, a pointer to a "resource" on the World Wide Web. A resource can be something as simple as a file or a directory, or it can be a reference to a more complicated object, such as a query to a database or to a search engine.

HttpURLConnection: The abstract class URLConnection is the superclass of all classes that represent a communications link between the application and a URL. Instances of this class can be used both to read from and to write to the resource referenced by the URL. In general, creating a connection to a URL is a multistep process:
 
Method name:
openConnection():Manipulate parameters that affect the connection to the remote resource.

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

import org.json.JSONException;
import org.json.JSONObject;

public class HttpServiceHandler {
    URL url;
    HttpURLConnection connection;
    DataOutputStream dataOutputStrea;

    public static void main(String[] args) {
       String path = "http://localhost:90/testmethod/postdata";
       String method = "POST";
      
       try {
           HttpServiceHandler serviceHandler= new HttpServiceHandler(path, method);
           serviceHandler.setParameter(serviceHandler.getJson());
           System.out.println(serviceHandler.getResponse());
       } catch (Exception e) { 
           e.printStackTrace();
       }
    }
   
    public HttpServiceHandler(String requestUrl, String methodType) throws IOException{
       url = new URL(requestUrl);
       connection = (HttpURLConnection) url.openConnection(); 
       connection.setDoOutput(true);
       connection.setDoInput(true);
       connection.setInstanceFollowRedirects(false);
       connection.setRequestMethod(methodType);
       connection.setRequestProperty("Content-Type", "application/json");
       connection.setRequestProperty("charset", "utf-8");
       connection.setUseCaches (false);
      
       dataOutputStrea = new DataOutputStream(connection.getOutputStream ());
    }
   
    public void setParameter(JSONObject queryParameter) throws IOException{
       dataOutputStrea.writeBytes(queryParameter.toString());
       dataOutputStrea.flush();
       dataOutputStrea.close();
    }
   
    public String getResponse() throws IOException {
       StringBuilder response = new StringBuilder();
       int responseCode = connection.getResponseCode();

       if (responseCode == HttpsURLConnection.HTTP_OK) {
           String line;
           BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
           while ((line = br.readLine()) != null) {
              response.append(line);
           }
       } else {
           response.append("");
       }
       return response.toString();
    }
   
   
    private JSONObject getJson() throws JSONException{
       JSONObject jsonParam = new JSONObject();
       jsonParam.put("Username", "user1");
       jsonParam.put("Pasword", "123456");
       return jsonParam;
    }
}