HttpRequest POST to RESTful web service - Salesforce Apex Ca

本文关键字:Salesforce Apex Ca service web POST to RESTful HttpRequest | 更新日期: 2023-09-27 18:18:38

我创建了一个RESTful web服务(c#, WCF),它实现了以下接口:

public interface ITestService
{
    [OperationContract]
    [WebInvoke(Method = "POST",
     ResponseFormat = WebMessageFormat.Json,
     BodyStyle = WebMessageBodyStyle.Bare,
     UriTemplate = "?s={aStr}")]
    string Test(string aStr);
}

其中Test()方法只返回给定的任何内容(或默认的"test"字符串)- 以及方法被调用时的时间戳

该服务是公开可用的所以当我在任何浏览器中输入url时:

http://xx.xxx.xxx.xx:41000/TestService/web/

它返回json "test"字符串(或任何可能以?s=...结尾输入的字符串)。


我想要Salesforce向这个web服务发布数据。

我的apex类看起来是这样的-当一个对象插入Salesforce时,它被触发:

public class WebServiceCallout 
{
    @future (callout=true)
    public static void sendNotification(String name) 
    {
        HttpRequest req = new HttpRequest();
        HttpResponse res = new HttpResponse();
        Http http = new Http();
        req.setEndpoint('http://xx.xxx.xxx.xx:41000/TestService/web/');
        req.setMethod('POST');
        req.setHeader('Content-Type', 'application/json');
        req.setBody('');
        try 
        {
            res = http.send(req);
        } 
        catch(System.CalloutException e) 
        {
            System.debug('Callout error: '+ e);
            System.debug(res.toString());
        }
    }
}

当一个对象插入到Salesforce中时,Apex Jobs部分表示sendNotification()方法已经完成。但该服务从未通过该方法获取POST。(备注:远程站点设置中增加了服务IP)

我的语法有问题吗?

(在这个阶段,我只想让Salesforce调用web服务——甚至不向它发送任何内容)


作为一个例子,我已经创建了一个示例Console Application,它可以很好地发送到服务。

internal static void Main(string[] args)
{
    Uri address = new Uri("http://xx.xxx.xxx.xx:41000/TestService/web/");
    // Create the web request
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(address);
    // Set type to POST
    request.Method = "POST";
    request.ContentType = "application/json";
    // Create the data we want to send  
    var postData = "";
    // Create a byte array of the data we want to send
    var byteData = UTF8Encoding.UTF8.GetBytes(postData);
    // Set the content length in the request headers
    request.ContentLength = byteData.Length;
    // Write data
    using (var stream = request.GetRequestStream())
    {
        stream.Write(byteData, 0, byteData.Length);
    }
    // Get response  
    var response = (HttpWebResponse)request.GetResponse();
    var responseString = new StreamReader(
        response.GetResponseStream()
        ).ReadToEnd();
    Console.Writeline(responseString);
}

为什么我的Apex类在Salesforce callout不正确?

HttpRequest POST to RESTful web service - Salesforce Apex Ca

我找到了问题所在。我没有在远程站点设置中指定端口(什么!!)

上面的代码示例应该可以完美地工作(至少对我来说是这样的)


给将来遇到这个问题的人的提示:

在<<p> strong>设置 -> 安全 -> 远程站点设置

服务(远程站点URL)应该是这样的格式-无论你在哪里托管它:

http://xx.xxx.xxx.xx:41000
要测试上述代码,请执行: (你的名字)

-> 开发人员控制台 -> 调试 -> 执行匿名窗户打开

并复制以下行:

WebServiceCallout.sendNotification('Test');

,点击执行

执行代码,您应该看到执行日志(以及其中的任何错误)。