Tuesday 8 December 2015

How do you consume a RESTFUL webservice?


###########################
######Rest Provider code#####
##########################

@Controller
@Scope("request")
@RequestMapping(value = "/v1/program")
public class ProgramController {

@Autowired
@Qualifier("ProgramService")
private IProgramService iProgramService;

@RequestMapping(value = ProgramURIConstant.ADD_PROGRAM, method = RequestMethod.POST, produces = { MediaType.APPLICATION_JSON_VALUE })
public @ResponseBody
String addProgram(@RequestBody ProgramVO programVO) {
programVO.setTimestamp(DateUtils.getCurrentTimeIntoTimestamp());
String result = iProgramService.addProgram(programVO);
return result;
}

}

 Step-1
 Access the RestTemplate Bean

<beans>
<bean id="crestTemplate" class="org.springframework.web.client.RestTemplate">
</bean>          
</beans> 

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("rest-template.xml");
RestTemplate restTemplate = (RestTemplate) applicationContext.getBean("crestTemplate"); 


 Step-2

Define Accept Media (Which is responsible for output format from Restful Web service)

List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>();
acceptableMediaTypes.add(MediaType.APPLICATION_JSON);


Step-3

Creating HttpHeader object

HttpHeaders headers = new HttpHeaders();


Step-4
Setting Accept media inside the header
// what output we are expecting
headers.setAccept(acceptableMediaTypes);


Step-5
Setting Content Type iinside the header

// /We are setting the format of data which will from client to server
headers.setContentType(MediaType.APPLICATION_JSON);


Step-6

Define JSON Data which we want to send to the provider

ProgramVO programVO=new ProgramVO();
programVO.setCode("fororueueueueu");
programVO.setId("P039393");
programVO.setLanguage("Kava");
programVO.setLevel("1");
programVO.setProgramTiitle("Binary Nuber");
programVO.setTopic("Coding");
programVO.setUserid("akash");


Step-7
// setting header and data inside the HttpEntity which will work as a request
//in Restful communication
HttpEntity<ProgramVO> requestEntity = new HttpEntity<ProgramVO>(programVO,headers);


Step-8
Calling the Restful web service

ResponseEntity<String> response = restTemplate.exchange("http://www.gpsprogramys.co.in/com.gps.quiz/android/v1/program/add", HttpMethod.POST, requestEntity,String.class);

String output=response.getBody();







No comments:

Post a Comment