如何从 D365 X++ 服务器调用 REST API 到另一台服务器(财务和运营)

问题描述 投票:0回答:1

我有一个 xyz.com 服务器的 get/post 请求,我需要使用 X++ 调用它来获取它的响应并在我的业务逻辑中使用。

我尝试使用一些 BlogSpot 文章中的代码,但没有工作并且给出了错误的请求。那么您能否帮助修复此代码或建议任何其他正确的代码以获得外部服务的响应。

` 公共静态无效主(参数_args)

{

    str destinationUrl = {{url}};

    str requestJson, responseJson;

    System.Net.HttpWebRequest request;

    System.Net.HttpWebResponse response = new System.Net.HttpWebResponse();

    CLRObject clrObj;

    System.Byte[] bytes;

    System.Text.Encoding utf8;

    System.IO.Stream requestStream, responseStream;

    System.IO.StreamReader streamReader;

    System.Exception ex;

    System.Net.WebHeaderCollection httpHeader;

    System.Net.ServicePoint servicePt;

    str byteStr;

    System.Byte[] byteArray;

    System.IO.Stream stream;

    System.IO.Stream dataStream;

    requestJson =  {{payload}};

    try

    {

        new InteropPermission(InteropKind::ClrInterop).assert();

        httpHeader = new System.Net.WebHeaderCollection();

        request = System.Net.WebRequest::Create(destinationUrl);

        utf8 = System.Text.Encoding::get_UTF8();

        bytes = utf8.GetBytes(requestJson);

        request.set_Method("POST");

        httpHeader.Add("Content-Type:text/html; charset=utf-8");

        httpHeader.Add("Pass Owner Id");

        httpHeader.Add("GSTIN");

        request.set_Headers(httpHeader);

        request.set_ContentLength(bytes.get_Length());

        requestStream = request.GetRequestStream();

        requestStream.Write(bytes, 0, bytes.get_Length());

        response = request.GetResponse();

        responseStream = response.GetResponseStream();

        streamReader = new System.IO.StreamReader(responseStream);

        responseJson = streamReader.ReadToEnd();

        info(responseJson);

    }
    catch (Exception::CLRError)

    {

        ex = CLRInterop::getLastException().GetBaseException();

        error(ex.get_Message());

    }

    requestStream.Close();

    streamReader.Close();

    responseStream.Close();

    response.Close();

} 
x++ dynamics-365
1个回答
0
投票

通过添加和注释此代码的几个部分来修复此问题:

new InteropPermission(InteropKind::ClrInterop).assert();

        httpHeader = new System.Net.WebHeaderCollection();

        request = System.Net.WebRequest::Create(destinationUrl);

        utf8 = System.Text.Encoding::get_UTF8();

        bytes = utf8.GetBytes(requestJson);

        request.set_Method("POST");

    //    httpHeader.Add("Content-Type:text/html; charset=utf-8");

     //   httpHeader.Add("Pass Owner Id");

      //  httpHeader.Add("GSTIN");

        request.set_Headers(httpHeader);

        request.ContentType = 'application/json';

        request.set_ContentLength(bytes.get_Length());
© www.soinside.com 2019 - 2024. All rights reserved.