Monday 18 July 2016

X++: HTTP Web Request to URL

//This method makes HTTP web request to the given url and returns the response
System.Net.WebRequest webrequest;

System.Net.HttpWebResponse httpresponse;

System.IO.Stream stream;

System.IO.StreamReader streamReader;

xml responseXML;

System.Byte[] arrayOfBytes;

System.Text.Encoding encoding;
System.String netString = "Net string.";
  System.Exception netExcepn;

;

try

{

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

//Use .Net framework reflections to make HttpRequest and get the response back

encoding = System.Text.Encoding::get_UTF8();
arrayOfBytes = encoding.GetBytes("");

webrequest = System.Net.WebRequest::Create('http://localhost/AxService/myService.asmx/HelloWorld');

webrequest.set_Method("POST");
webrequest.set_PreAuthenticate(true);
webrequest.set_Credentials(System.Net.CredentialCache::get_DefaultCredentials());

webrequest.set_ContentType("application/x-www-form-urlencoded");
webrequest.set_ContentLength(arrayOfBytes.get_Length());
stream = webrequest.GetRequestStream();
stream.Write(arrayOfBytes,0,arrayOfBytes.get_Length());
stream.Close ();



httpresponse = webrequest.GetResponse();

stream = httpresponse.GetResponseStream ();

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

responseXML = streamReader.ReadToEnd ();

streamReader.Close ();

stream.Close ();

httpResponse.Close ();



codeAccessPermission::revertAssert();
    info(responseXML);
}

 catch (Exception::Error)
    {
        info("Caught 'Exception::Error'.");
    }
    catch (Exception::CLRError)
    {
        info("Caught 'Exception::CLRError'.");
        netExcepn = CLRInterop::getLastException();
        info(netExcepn.ToString());
    }

No comments:

Post a Comment