• Vishal Dube 1
  • NEWBIE
  • 5 Points
  • Member since 2014

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 1
    Questions
  • 3
    Replies
I am trying to make an asynchronous call to a wordpress site using HTTP callout method( using @Future). Everything works on sandbox and I was able to get 60% code coverage after hours of hit and trial methods. The issue started when it was deployed to production box, I am getting timeout error for every call to wordpress. I tried using request.timeout property with values ranging from 2 seconds to 120 seconds. Even then it gives me request time out error 408. My understanding with timeout is it will wait for specified time for a response before terminating with error. Also when it is an asychronous call, there should be no response. Please provide expert opinion on this topic. Below is my code
public class Wordpress_AsyncCall {
    
    @future (callout=true)
    public static void callwordpress(string endp){
        Httprequest req = new HttpRequest();
        req.setEndpoint(endp);
        req.setMethod('GET');
        req.setCompressed(true); // otherwise we hit a limit of 32000
      
        Http http = new Http();
        try{
        http.send(req);
        }
        catch(System.CalloutException e) {
           System.debug('Callout error: '+ e);
           }
        
   }
I am trying to make an asynchronous call to a wordpress site using HTTP callout method( using @Future). Everything works on sandbox and I was able to get 60% code coverage after hours of hit and trial methods. The issue started when it was deployed to production box, I am getting timeout error for every call to wordpress. I tried using request.timeout property with values ranging from 2 seconds to 120 seconds. Even then it gives me request time out error 408. My understanding with timeout is it will wait for specified time for a response before terminating with error. Also when it is an asychronous call, there should be no response. Please provide expert opinion on this topic. Below is my code
public class Wordpress_AsyncCall {
    
    @future (callout=true)
    public static void callwordpress(string endp){
        Httprequest req = new HttpRequest();
        req.setEndpoint(endp);
        req.setMethod('GET');
        req.setCompressed(true); // otherwise we hit a limit of 32000
      
        Http http = new Http();
        try{
        http.send(req);
        }
        catch(System.CalloutException e) {
           System.debug('Callout error: '+ e);
           }
        
   }

I am using an Apex trigger and asynchronous method to perform a callout to the JSON REST API for Wordpress. I continue to receive 500 Internal Server Error responses in my debug log when I edit a Salesforce record, but if I copy/paste the corresponding JSON into the Postman plug-in for Chrome the post is created as expected. Any help is appreciated, thanks!

 

trigger insertPost on Custom_Object__c (after insert, after update) {
    String theIds = '';
    for (Custom_Object__c c : Trigger.new) {
        if (theIds == '')
            theIds = c.Id;
        else
            theIds += '|' + c.Id;
    }
    //Make asynchronous web service callout to insert post
    if (theIds != '')
        WebServiceCallout.sendPost(theIds);
}

 

public class WebServiceCallout {
 
    @future (callout=true)
    public static void sendPost(String theIds) {
 
        HttpRequest req = new HttpRequest();
        HttpResponse res = new HttpResponse();
        Http http = new Http();
        
        if(Test.isRunningTest()){
            Website_Settings__c wpSettings = new Website_Settings__c(Wordpress_URL__c = 'https://testing.com/', Wordpress_Username__c = 'Test', Wordpress_Password__c = 'Test');        
            insert wpSettings;
        }
        
        //Set Headers from Custom Settings & Visualforce
        Website_Settings__c wpSettings = Website_Settings__c.getInstance();
        if (wpSettings.Wordpress_URL__c!=null && wpSettings.Wordpress_Username__c!=null && wpSettings.Wordpress_Password__c!=null){
            
            //Set Endpoint
            String endpoint = wpSettings.Wordpress_URL__c;
            if (endpoint.endsWith('/'))
                req.setEndpoint(endpoint+'wp-json.php/posts/');
            else
                req.setEndpoint(endpoint+'/wp-json.php/posts/');
            
            //Set Method
            req.setMethod('POST');
            
            //Specify the required user name and password to access the endpoint
            String username = wpSettings.Wordpress_Username__c;
            String password = wpSettings.Wordpress_Password__c;
            Blob headerValue = Blob.valueOf(username + ':' + password);
            String authorizationHeader = 'Basic ' + EncodingUtil.base64Encode(headerValue);
            req.setHeader('Authorization', authorizationHeader);
            
            //Specify Content-Type
            req.setHeader('Content-Type', 'application/json');
            
            //Specify Cache-Control
            req.setHeader('Cache-Control', 'no-cache');
            
            //Set Body
            objectToJSON.theId = theIds;
            objectToJSON jsonClass = new objectToJSON();
            req.setBody(jsonClass.jsonData());
            
            try {
                System.debug(req.getHeader('Authorization'));
                System.debug(req.getHeader('Content-Type'));
                System.debug(req.getBody());
                if (!Test.isRunningTest())    
                    res = http.send(req);
            }
            
            catch(System.CalloutException e) {
                System.debug('Callout error: '+ e);
                System.debug(res.toString());
                System.debug(req.getBody());
            }
        
        }
 
    }
 
}

 

public with sharing class objectToJSON {
    //Global variables
    public static String theId;
    public list<String> theIds;
    public list<jsonObjectData> allObjects{get;set;}
    
    public objectToJSON() { 
        //***This method queries the database for information and converts it to JSON***
        //If URL parameters are set then query the database
        if (ApexPages.currentPage()!=null)
            if (ApexPages.currentPage().getParameters().get('theId')!=null && ApexPages.currentPage().getParameters().get('theId')!='')
                theId = String.escapeSingleQuotes(ApexPages.currentPage().getParameters().get('theId'));
        if (theId.contains('|'))
            theIds = theId.split('\\|',-1);
        else{
            theIds = new list<String>();
            theIds.add(theId);
        }
        allObjects = new list<jsonObjectData>();
        list<Custom_Object__c> objects = [SELECT Id, Name, Description__c, A__c, B__c, C__c FROM Custom_Object__c WHERE Id IN :theIds LIMIT 10000];
        for (Custom_Object__c o : objects){
            allObjects.add(new jsonObjectData(o));          
        }
    }
    
    public String jsonData() {
        String jsonData = '[';
        Integer x=0;
        while (allObjects.size()>x) {
            if (x==0)
                jsonData += '{';
            else
                jsonData += ',{';
            jsonObjectData o = allObjects[x];
            jsonData += '\"title\":\"'+o.name.replace('\"','\\"')+'\",';
            jsonData += '\"status\":\"publish\",';
            jsonData += '\"type\":\"custom\",';
            jsonData += '\"content_raw\":\"'+o.content.replace('\"','\\"').replace('\n','')+'\",';
            jsonData += '\"excerpt_raw\":\"'+o.excerpt.replace('\"','\\"').replace('\n','')+'\",';
            jsonData += '\"comment_status\":\"closed\"';
            jsonData += '}';
            x++;
        }
        jsonData += ']';
        if (x==1){
//Remove array formatting for individual post jsonData = jsonData.substring(1); jsonData = jsonData.substring(0,jsonData.length()-1); } return jsonData; } public class jsonObjectData { //*****Wrapper Class***** //Global variables for wrapper class public String name{get;set;} public String content{get;set;} public String excerpt{get;set;} public jsonObjectData(Custom_Object__c o) { //***Constructor method to create a JSON object*** //Define content variables String a = ''; String b = ''; String c = ''; //Set content variables if (o.A__c!=null) a = String.valueOf(o.A__c); if (o.B__c!=null) b = String.valueOf(o.B__c); if (o.C__c!=null) c = String.valueOf(o.C__c); //Define & Set description variable String description = ''; if (o.Description__c!=null) description = String.valueOf(o.Description__c); //Set name name = o.Name; //Set content content = '<div class="custom"></div>\n<div class="row clearfix ">\n<div class="col col_1_2 ">\n<div class="inner">\n<div class="styled_table table_blue">\n<table>\n<thead>\n<tr>\n<th>Custom</th>\n<th> </th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>A</td>\n<td>'+a+'</td>\n</tr>\n<tr>\n<td>B</td>\n<td>'+b+'</td>\n</tr>\n<tr>\n<td>C</td>\n<td>'+c+'</td>\n</tr>\n</tbody>\n</table>\n</div>\n</div>\n</div>\n</div>\n'; //Set excerpt excerpt = '<p>'+description+'</p>\n'; } } }

 

I am trying to connect to carrier 411 webservice to pull some data but keep getting the below error everytime I call.  If i use the same soap request in SOAP UI tool its giving me soap response.  Could anyone please shed some light into it.

 

 

11:54:28.084 (84661000)|CALLOUT_REQUEST|[56]|System.HttpRequest[Endpoint=http://webservices.carrier411.com/wsLogin.cfc, Method=POST]
11:54:28.418 (418009000)|CALLOUT_RESPONSE|[56]|System.HttpResponse[Status=Moved Temporarily, StatusCode=302]

 

 

Below is the soap request

 

<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <soap:Body>
    <login xmlns="http://webservices.carrier411.com">
      <param1>user</param1>
      <param2>password</param2>
    </login>
  </soap:Body>
</soap:Envelope>

 

this is how i am calling the service,,,

 public static string getResponse(String request,String URL)
  {
    try{
      Http h = new Http();
      HttpRequest req = new HttpRequest();
       req.setHeader('Content-Type','text/xml;charset=utf-8');
      req.setMethod('POST');
      req.setEndpoint(URL);
      req.setBody(request);
      req.setTimeout(2000);
      System.Debug('HTTP Request is ' + req);
      HttpResponse res = h.send(req);
      
      System.Debug('HTTP Resonse is ' + res);
      return res.getBody();
    }
    catch(Exception ex) {
        throw ex;
        }
  }
 

This is the webservice  I am trying to call...I am not sure whether  i am missing anything in the header part....

webservices.carrier411.com/wsLogin.cfc?wsdl