Search code examples
salesforceapex-code

POST Request unable to receive the JSON respose in Salesforce


I am calling an API of FluidSurvey. when i make a POST request ... it post the request on the fluidSurvey but i didnt get the JSON response. rather it returns nothing. any suggestion??

my controller code

public class fluidSurvey{

public String tst{set;get;}
public String result{get;set;}

public PageReference chk() {
    getData();
    return null;
}

public void getData(){
    String apiKey = 'xxxxxx';
    String pwd = 'xxxxxx';
    String u = 'https://app.fluidsurveys.com/api/v2/surveys/survey_id/responses/';

    HttpRequest req = new HttpRequest();
    Http http = new Http();
    HTTPResponse res;
    try{
        req.setEndPoint(u);
        req.setTimeout(2000);
        req.setMethod('POST');
        Blob headerValue = Blob.valueOf(apikey + ':' + pwd);
        String authorizationHeader = 'Basic '+ EncodingUtil.base64Encode(headerValue);
        req.setHeader('Authorization', authorizationHeader);
        req.setHeader('Content-Type', 'application/json');
        req.setHeader('Content-Length','31999');

        res = http.send(req); 
        tst= res.toString();



       catch(Exception e){
           System.debug('Callout error: '+ e);
           System.debug(tst+'--------'+res);
       }     
    }

}

and the Apex page code is

<apex:page controller="fluidSurvey">

<apex:form >
    <apex:pageBlock title="New Fluid Surveys API">
    <apex:outputText value="{!tst}"></apex:outputText><br/>
<apex:pageBlockButtons location="bottom">
    <apex:commandButton value="Submit" action="{!chk}"/>
</apex:pageBlockButtons>   
</apex:pageBlock>
</apex:form>

and api documentation link is http://docs.fluidsurveys.com/api/surveys.html#getting-a-list-of-surveys..


Solution

  • The problem with my code was that i setting a content-length header, but not setting any body,the server is diligently waiting for the 3199 byte body. so after using the setBody method my code properly returns a json response