Simple REST API calls using Spring?

Ok, I have a simple REST API running now. I also have a mobile app (Android) that will be ready for some network communications. But here's what:

Now I have a fantastic API built with Spring that I can use with Http-Requests:

package com.helloworld

@Controller
@RequestMapping("/helloWorld")
public class HelloWorldController {

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String hello(ModelMap model) {
        model.addAttribute("msg", "JCG Hello World!");
        return "helloWorld";
    }
}

      

Everything is fine, but how can I use this API in my android android app? I mean, I don't know how to make these calls more elegant and simple! I don't want to write something like this for every request on my API:

class HelloWorldTask extends AsyncTask<String, String, String> {

    private String url = "http://192.168.42.229:8080/HelloWorldExample/helloWorld/displayMessage/" + msg; 

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

        String msg = "";
        for(String m : uri) { msg += m; }    

        RestTemplate restTemplate = new RestTemplate();    
        restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
        return restTemplate.getForObject(url, String.class, "Android");
    }
}

      

Is there a way to avoid this? To be honest, I figured that after building my REST API project, I would be able to import something like helloworld-api.jar

and then do something like this:

import com.helloworld

public void getServerHello() {

    HelloWorldController api;

    HelloWorld helloWorld = api.getHelloWorldMapping();
    helloWorld.displayMessage("How are you?");
}

      

And it will be so. So, is there a way to do something like this when writing a Spring REST API or do I really need to use something like a builder URI and create an extra one for all request types class <whatever>Task extends AsyncTask<?, ?, ?>

myself?

Since the API is well defined, it should be possible to do something like this, but right?

I hope my question is clear - please let me know if not.

+3


source to share


5 answers


In my current project, we have a similar setup with a Java client and a RESTful backend based on the Springs REST API. We use apache-cxf-rs-client-api

to call our REST services from clients.



  • Create an interface for your methods in HelloWorldController

    .

  • Add apache-cxf-rs-client-api

    to your project (see details ).

  • Now you can call the interface on the client and Apache CXF will do everything for you.

0


source


import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriComponentsBuilder;

import com.itech.payroll.dto.ComypanyDTO;
import com.itech.payroll.dto.EmployeeDTO;
import com.itech.payroll.dto.User;
import com.itech.payroll.repo.PayrollRepo;
import com.itech.payroll.service.PayrollService;
import com.itech.payroll.service.UserService;
/**
 * REST API Implementation Using REST Controller
 * */
@RestController
public class RestReqCntrl {

    @Autowired
    private UserService userService;    

    @Autowired
    private PayrollService payrollService;  


    //-------------------Create a User--------------------------------------------------------

    @RequestMapping(value = "/registerUser", method = RequestMethod.POST)
    public ResponseEntity<User> registerUser(@RequestBody User user,    UriComponentsBuilder ucBuilder) throws Exception {
        System.out.println("Creating User " + user.getFirstName());

        boolean flag = userService.registerUser(user);

         if (flag)
         {
             user.setStatusCode(1);
             user.setStatusDesc("PASS");
         }else{
             user.setStatusCode(0);
             user.setStatusDesc("FAIL");

         }

        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(ucBuilder.path("/registerUser").buildAndExpand(user.getId()).toUri());
        return new ResponseEntity<User>(user,headers, HttpStatus.CREATED);
    }   

    //-------------------Authenticating the User--------------------------------------------------------

    @RequestMapping(value = "/authuser", method = RequestMethod.POST)
    public ResponseEntity<User> authuser(@RequestBody User user,UriComponentsBuilder ucBuilder) throws Exception {
        System.out.println("Creating User " + user.getFirstName());

        boolean flag = userService.authUser(user);

         if (flag)
         {
             user.setStatusCode(1);
             user.setStatusDesc("PASS");
         }else{
             user.setStatusCode(0);
             user.setStatusDesc("FAIL");

         }

        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(ucBuilder.path("/authuser").buildAndExpand(user.getFirstName()).toUri());
        return new ResponseEntity<User>(user,headers, HttpStatus.ACCEPTED);
    }   

    //-------------------Create a Company--------------------------------------------------------
    @RequestMapping(value = "/registerCompany", method = RequestMethod.POST)
    public ResponseEntity<String> registerCompany(@RequestBody ComypanyDTO comypanyDTO, UriComponentsBuilder ucBuilder) throws Exception {
        System.out.println("Creating comypanyDTO " + comypanyDTO.getCmpName());
        String result ="";
        boolean flag = payrollService.registerCompany(comypanyDTO);

         if (flag)
         {
             result="Pass";
         }else{
             result="Fail";

         }

        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(ucBuilder.path("/registerCompany").buildAndExpand(result).toUri());
        return new ResponseEntity<String>(result,headers, HttpStatus.ACCEPTED);
    }   


    //-------------------Create a Employee--------------------------------------------------------
    @RequestMapping(value = "/registerEmployee", method = RequestMethod.POST)
    public ResponseEntity<String> registerEmployee(@RequestBody EmployeeDTO employeeDTO, UriComponentsBuilder ucBuilder) throws Exception {
        System.out.println("Creating registerCompany " + employeeDTO.getEmpCode());
        String result ="";
        boolean flag = payrollService.registerEmpbyComp(employeeDTO);

         if (flag)
         {
             result="Pass";
         }else{
             result="Fail";

         }

        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(ucBuilder.path("/registerCompany").buildAndExpand(result).toUri());
        return new ResponseEntity<String>(result,headers, HttpStatus.ACCEPTED);
    }   

    //-------------------Get Company Deatils--------------------------------------------------------
    @RequestMapping(value = "/getCompanies", method = RequestMethod.GET)
    public ResponseEntity<List<ComypanyDTO> > getCompanies(UriComponentsBuilder ucBuilder) throws Exception {
        System.out.println("getCompanies getCompanies ");
        List<ComypanyDTO> comypanyDTOs =null;
        comypanyDTOs = payrollService.getCompanies();
        //Setting the Respective Employees
        for(ComypanyDTO dto :comypanyDTOs){

            dto.setEmployeeDTOs(payrollService.getEmployes(dto.getCompanyId()));
        }

        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(ucBuilder.path("/registerCompany").buildAndExpand("LISt").toUri());
        return new ResponseEntity<List<ComypanyDTO>>(comypanyDTOs,headers, HttpStatus.ACCEPTED);
    }   

}

      



+1


source


Annotate your method with @ResponseBody

@Controller
@RequestMapping("/helloWorld")
public class HelloWorldController {

    @RequestMapping(value = "/hello", method = RequestMethod.GET, produces="application/json")
    @ResponseBody
    public String hello(ModelMap model) {
        model.addAttribute("msg", "JCG Hello World!");
        return "helloWorld";
    }
}

      

If the method is annotated with @ResponseBody, the return type is written to the response body of the response. The above example will cause the text helloWorld to be written to the HTTP response stream.

Write an Android Http client that will send an Http request to your Spring app, the response will be in JSON format. Parse the JSON through JQuery and display the data.

0


source


Check out Volley or Retrofit. The latter is especially useful for quickly configuring client-side APIs.

When I do something like this, I usually reuse the server model if available (when I do both client and server, for example).

Otherwise, you can just convert the json to the pojo class and use it using Retrofit.

0


source


To write api you need to follow below pattern:

com.helloworld package

@Controller
@RequestMapping("/api")
public class HelloWorldController {
    @ResponseBody
    @RequestMapping(value = "/helloworld", method = RequestMethod.GET)
    public String hello() {
        return "helloWorld";
    }
}

      

For more information on step by step training you can follow the link .

0


source







All Articles