How to Send and Receive Data from Web Services

Web Services are the best part of Salesforce Development through which one can able to make the code available on the network for use. Through  web services you can either get data from it or you can send the data to web services as well. By the help of this blog let me try to explore the way of doing both.

For Getting the data from web service we use 'GET' method with the relevant endpoints.

By using the below syntax of code we can achieve it successfully.

Http http =new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('---any---');
request.setMethod('GET');
HtttpResponse response = Http.send(request);
if(response.getStatusCode() == 200){
Map<String,Object> results = (Map<String,Object>)JSON.deserializeuntyped(response.getBody());
}

In the same pattern by using HTTP as a protocol with Body, Header, Endpoints, and keeping the method 'POST' we can able to send data to web service.

Below is the helping code to achieve it.

Http http =new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('---any---');
request.setMethod('POST');
request.setHeader('Content-Type', 'application/json', 'charset=UTF-8');
request.setBody('{"name":"Test-Only"}');
HtttpResponse response = Http.send(request);
if(response.getStatusCode != 201){
System.debug('System status code not expected'+ response.getStatusCode()+' '+response.getStatus());
}
else{
System.debug(response.getBody());
}

Let's have a try to do so for having the good usage of web services for either sending data or getting data from Web Services.

Thanks For Reading!!

Happy Salesforce!!

Responses

Popular Salesforce Blogs