I have a get/post request of an xyz.com server, and I need to call that using X++ to fetch it's response and use in my business logic.
I tried using this code from some BlogSpot article, but was not working and giving bad request. So can you please help to fix this code or suggest any other proper code to get response from external service.
public static void main(Args _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();
}
Fixed this, by adding and commenting few parts of this code: