I am trying to post a request in a C# Console Application and I am getting this error. The request is working in SOAPUI, there is no WSDL File so I have to load the XML directly in the code (I highly suspect this is where the error is coming from).
The output on the Console Application is below:
The SOAPUI Request that is working is as Follows:
Here is the C# Console Application that I am using to send this SOAP Request.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace IMSPostpaidtoPrepaid
{
class Program
{
static void Main(string[] args)
{
Program obj = new Program();
obj.createSOAPWebRequest();
}
//Create the method that returns the HttpWebRequest
public void createSOAPWebRequest()
{
//Making the Web Request
HttpWebRequest Req = (HttpWebRequest)WebRequest.Create(#"http://127.1.1.0:9090/spg");
//Content Type
Req.ContentType = "text/xml;charset=utf-8";
Req.Accept = "text/xml";
//HTTP Method
Req.Method = "POST";
//SOAP Action
Req.Headers.Add("SOAPAction", "\"SOAPAction:urn#LstSbr\"");
NetworkCredential creds = new NetworkCredential("username", "pass");
Req.Credentials = creds;
Req.Headers.Add("MessageID", "1"); //Adding the MessageID in the header
string DN = "+26342720450";
string DOMAIN = "ims.telone.co.zw";
//Build the XML
string xmlRequest = String.Concat(
"<?xml version=\"1.0\" encoding=\"utf-8\"?>",
"<soap:Envelope",
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"",
" xmlns:m=\"http://www.huawei.com/SPG\"",
" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"",
" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">",
" <soap:Body>",
"<m:LstSbr xmlns=\"urn#LstSbr\">",
" < m:DN >", DN, "</ m:DN>",
" < m:DOMAIN >", DOMAIN, "</ m:DOMAIN>",
" </m:LstSbr>",
" </soap:Body>",
"</soap:Envelope>");
//Pull Request into UTF-8 Byte Array
byte[] reqBytes = new UTF8Encoding().GetBytes(xmlRequest);
//Set the content length
Req.ContentLength = reqBytes.Length;
//Write the XML to Request Stream
try
{
using (Stream reqStream = Req.GetRequestStream())
{
reqStream.Write(reqBytes, 0, reqBytes.Length);
}
}
catch (Exception ex)
{
Console.WriteLine("Exception of type " + ex.GetType().Name + " " + ex.Message );
Console.ReadLine();
throw;
}
//Headers and Content are set, lets call the service
HttpWebResponse resp = (HttpWebResponse)Req.GetResponse();
string xmlResponse = null;
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
xmlResponse = sr.ReadToEnd();
}
Console.WriteLine(xmlResponse);
Console.ReadLine();
}
}
}
Here is my basic method that I use to post to a web service.
static XNamespace soapNs = "http://schemas.xmlsoap.org/soap/envelope/";
static XNamespace topNs = "Company.WebService";
private System.Net.HttpWebResponse ExecutePost(string webserviceUrl, string soapAction, string postData) {
var webReq = (HttpWebRequest)WebRequest.Create(webserviceUrl);
webReq.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
webReq.ContentType = "text/xml;charset=UTF-8";
webReq.UserAgent = "Opera/12.02 (Android 4.1; Linux; Opera Mobi/ADR-1111101157; U; en-US) Presto/2.9.201 Version/12.02";
webReq.Referer = "http://www.company.com";
webReq.Headers.Add("SOAPAction", soapAction);
webReq.Method = "POST";
var encoded = Encoding.UTF8.GetBytes(postData);
webReq.ContentLength = encoded.Length;
var dataStream = webReq.GetRequestStream();
dataStream.Write(encoded, 0, encoded.Length);
dataStream.Close();
System.Net.WebResponse response;
try { response = webReq.GetResponse(); }
catch {
("Unable to post:\n" + postData).Dump();
throw;
}
return response as System.Net.HttpWebResponse;
}
I then can build whatever I want around this to do what I need. For example here is how I would use it.
private void CreateTransaction(string webServiceUrl, string ticket, double costPerUnit) {
string soapAction = "Company.WebService/ICompanyWebService/CreatePurchaseTransaction";
var soapEnvelope = new XElement(soapNs + "Envelope",
new XAttribute(XNamespace.Xmlns + "soapenv", "http://schemas.xmlsoap.org/soap/envelope/"),
new XAttribute(XNamespace.Xmlns + "top", "Company.WebService"),
new XElement(soapNs + "Body",
new XElement(topNs + "CreatePurchaseTransaction",
new XElement(topNs + "command",
new XElement(topNs + "BillTransaction", "true"),
new XElement(topNs + "BillingComments", "Created By C# Code"),
new XElement(topNs + "Department", "Development"),
new XElement(topNs + "LineItems", GetManualPurchaseLineItems(topNs, costPerUnit)),
new XElement(topNs + "Surcharge", "42.21"),
new XElement(topNs + "Tax", "true"),
new XElement(topNs + "TransactionDate", DateTime.Now.ToString("yyyy-MM-dd"))
))));
var webResp = ExecutePost(webServiceUrl, soapAction, soapEnvelope.ToString());
if (webResp.StatusCode != HttpStatusCode.OK)
throw new Exception("Unable To Create The Transaction");
var sr = new StreamReader(webResp.GetResponseStream());
var xDoc = XDocument.Parse(sr.ReadToEnd());
var result = xDoc.Descendants(topNs + "ResultType").Single();
if (result.Value.Equals("Success", StringComparison.CurrentCultureIgnoreCase) == false)
throw new Exception("Unable to post the purchase transaction. Look in the xDoc for more details.");
}
private IEnumerable<XElement> GetManualPurchaseLineItems(XNamespace topNs, double costPerUnit) {
var lineItems = new List<XElement>();
lineItems.Add(new XElement(topNs + "PurchaseLineItem",
new XElement(topNs + "Count", "5"),
new XElement(topNs + "ExpenseClass", "Tech Time"),
new XElement(topNs + "ItemName", "Brushing and Flossing"),
new XElement(topNs + "Location", "Your House"),
new XElement(topNs + "UnitCost", costPerUnit.ToString("#.00"))));
return lineItems;
}
You would need to adapt this into your console application, but does this help get you going?
Related
I have a 500 error when trying to consume a soap WS .
code below :
main function :
public void Main()
{
var action = "XXXXXX";
string result = SendSOAPRequest("http://XXXXXXXX:80/XXXX", action, new Dictionary<string, string>() , false);
}
sendrequest method :
public void Main()
{
var action = "XXXXXX";
string result = SendSOAPRequest("http://XXXXXXXX:80/XXXX", action, new Dictionary<string, string>() , false);
}
public static string SendSOAPRequest(string url, string action,Dictionary<string, string> parameters, bool useSOAP12 = false)
{
try{
XmlDocument soapEnvelopeXml = new XmlDocument();
var xmlStr = (useSOAP12)
? #"XXXXXX";
string parms = string.Join(string.Empty, parameters.Select(kv => String.Format("<{0}>{1}</{0}>", kv.Key, kv.Value)).ToArray());
var s = String.Format(xmlStr, action, new Uri(url).GetLeftPart(UriPartial.Authority) + "/", parms);
soapEnvelopeXml.LoadXml(s);
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(url + "/" + action));
webRequest.Headers.Add("SOAPAction", url);
webRequest.Headers.Add("XXXXXX", "AG6YUTGV6");
webRequest.ContentType = (useSOAP12) ? "application/soap+xml;charset=\"utf-8\"" : "text/xml;charset=\"utf-8\"";
webRequest.Accept = (useSOAP12) ? "application/soap+xml" : "text/xml";
webRequest.Method = "GET";
string usernamePassword = "username" + ":" + "pass";
usernamePassword = Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword));
CredentialCache mycache = new CredentialCache();
webRequest.Credentials = mycache;
webRequest.Headers.Add("Authorization", "Basic " + usernamePassword);
using (WebResponse response = webRequest.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
XmlTextReader reader = new XmlTextReader(stream);
}
}
using (Stream stream = webRequest.GetRequestStream())
{
soapEnvelopeXml.Save(stream);
}
string result;
using (WebResponse response = webRequest.GetResponse())
{
using (StreamReader rd = new StreamReader(response.GetResponseStream()))
{
result = rd.ReadToEnd();
}
}
return result;
}
catch (WebException ex)
{
string message = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
}
return "";
}
I am fairly new to programming. I require exception handling for my HttpWebRequest to an Api. Below is my code, I haven't done error handling before so just an example of how to accomplish this will be appreciated.
private void button1_Click(object sender, EventArgs e)
{
Class1.PostDevices x = new Class1.PostDevices();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(webAddr);
request.ContentType = "application/json";
request.Method = "POST";
request.Timeout = 5000;
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
string jsonstring;
MemoryStream stream1 = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Class1.PostDevices));
x.notification = new Class1.Notification();
x.profile = "dev";
x.notification.message = "Hello World";
ser.WriteObject(stream1, x);
stream1.Position = 0;
StreamReader sr = new StreamReader(stream1);
jsonstring = sr.ReadToEnd();
Debug.WriteLine(JObject.Parse(jsonstring));
streamWriter.Write(jsonstring);
streamWriter.Flush();
}
HttpWebResponse httpResponse = (HttpWebResponse)request.GetResponse();
if (httpResponse.StatusCode == HttpStatusCode.OK)
{
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
string result = streamReader.ReadToEnd();
Debug.WriteLine(JObject.Parse(result));
Reponse.PostDevicesReponse MyResult = JsonConvert.DeserializeObject<Reponse.PostDevicesReponse>(result);
}
}
}
}
1) Create a folder named as "ExceptionTextFile" inside your application
2) Create a Separate Class like below to log the exception
using System;
using System.IO;
using context = System.Web.HttpContext;
//Define your application namespace here
namespace YourApplicationNamespace
{
public static class ExceptionLogging
{
private static String ErrorlineNo, Errormsg, extype, exurl, ErrorLocation;
public static void SendErrorToText(Exception ex)
{
var line = Environment.NewLine + Environment.NewLine;
ErrorlineNo = ex.StackTrace.ToString();
Errormsg = ex.Message;
extype = ex.GetType().ToString();
exurl = context.Current.Request.Url.ToString();
ErrorLocation = ex.Message.ToString();
try
{
//Create a folder named as "ExceptionTextFile" inside your application
//Text File Path
string filepath = context.Current.Server.MapPath("~/ExceptionTextFile/");
if (!Directory.Exists(filepath))
{
Directory.CreateDirectory(filepath);
}
//Text File Name
filepath = filepath + DateTime.Today.ToString("dd-MM-yy") + ".txt";
if (!File.Exists(filepath))
{
File.Create(filepath).Dispose();
}
using (StreamWriter sw = File.AppendText(filepath))
{
string error = "Log Written Date:" + " " + DateTime.Now.ToString()
+ line + "Error Line No :" + " " + ErrorlineNo + line
+ "Error Message:" + " " + Errormsg + line + "Exception Type:" + " "
+ extype + line + "Error Location :" + " " + ErrorLocation + line
+ " Error Page Url:" + " " + exurl + line + line;
sw.WriteLine("-----------Exception Details on " + " " + DateTime.Now.ToString() + "-----------------");
sw.WriteLine("-------------------------------------------------------------------------------------");
sw.WriteLine(line);
sw.WriteLine(error);
sw.WriteLine("--------------------------------*End*------------------------------------------");
sw.WriteLine(line);
sw.Flush();
sw.Close();
}
}
catch (Exception e)
{
e.ToString();
}
}
}
}
After that inside your button click event define try...catch block and log the exception like below
private void button1_Click(object sender, EventArgs e)
{
try
{
Class1.PostDevices x = new Class1.PostDevices();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(webAddr);
request.ContentType = "application/json";
request.Method = "POST";
request.Timeout = 5000;
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
string jsonstring;
MemoryStream stream1 = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Class1.PostDevices));
x.notification = new Class1.Notification();
x.profile = "dev";
x.notification.message = "Hello World";
ser.WriteObject(stream1, x);
stream1.Position = 0;
StreamReader sr = new StreamReader(stream1);
jsonstring = sr.ReadToEnd();
Debug.WriteLine(JObject.Parse(jsonstring));
streamWriter.Write(jsonstring);
streamWriter.Flush();
}
HttpWebResponse httpResponse = (HttpWebResponse)request.GetResponse();
if (httpResponse.StatusCode == HttpStatusCode.OK)
{
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
string result = streamReader.ReadToEnd();
Debug.WriteLine(JObject.Parse(result));
Reponse.PostDevicesReponse MyResult = JsonConvert.DeserializeObject<Reponse.PostDevicesReponse>(result);
}
}
}
}
catch (Exception e)
{
ExceptionLogging.SendErrorToText(e);
}
}
If any error appears go to the "ExceptionTextFile" folder and check the log. The exception would be logged there.
Try and revert me back if this solves your problem or not
I would like to try upload a mp3 file to my soundcloud account. I have written this code for this job.
WebClient client = new WebClient();
string postData = "client_id=" + "xxxxx"
+ "&client_secret=" + "xxx"
+ "&grant_type=password&username=" + "xxx" //your username
+ "&password=" + "xxx";//your password :)
string soundCloudTokenRes = "https://api.soundcloud.com/oauth2/token";
string tokenInfo = client.UploadString(soundCloudTokenRes, postData);
tokenInfo = tokenInfo.Remove(0, tokenInfo.IndexOf("token\":\"") + 8);
string token = tokenInfo.Remove(tokenInfo.IndexOf("\""));
System.Net.ServicePointManager.Expect100Continue = false;
var request = WebRequest.Create("https://api.soundcloud.com/tracks") as HttpWebRequest;
request.CookieContainer = new CookieContainer();
//some default headers
request.Accept = "*/*";
request.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
request.Headers.Add("Accept-Encoding", "gzip,deflate,sdch");
request.Headers.Add("Accept-Language", "en-US,en;q=0.8,ru;q=0.6");
//file array
var files = new UploadFile[] { new UploadFile(filePath, "#/" + filePath, "application/octet-stream") };
//other form data
var form = new NameValueCollection();
form.Add("track[title]", "biksad");
form.Add("track[sharing]", "public");
form.Add("oauth_token", token);
form.Add("format", "json");
form.Add("Filename", fileName);
form.Add("Upload", "Submit Query");
string lblInfo;
try
{
using (var response = HttpUploadHelper.Upload(request, files, form))
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
lblInfo = reader.ReadToEnd();
}
}
}
catch (Exception ex)
{
lblInfo = ex.ToString();
}
}
When I debug this code part. I get (422) Unprocessable Entity error in catch block. Why I get this error? How can solve this problem?
Check the Soundcloud documentation:
http://developers.soundcloud.com/docs#errors
422 - "The request looks alright, but one or more of the parameters looks a little screwy. It's possible that you sent data in the wrong format (e.g. an array where we expected a string)."
Right now I get a full dump of this XML...
http://smart-ip.net/geoip-xml/68.5.63.33
What I want my program to do is just call the city and region from that XML.
I'm new to web services so I'm having trouble trying to figure out how to do this, help is much appreciated
Here is my code:
HttpWebRequest myHttpWebRequest = null;
HttpWebResponse myHttpWebResponse = null;
XmlTextReader myXMLReader = null;
try
{
XPathNavigator nav;
XPathDocument docNav;
String weatherURL = "http://smart-ip.net/geoip-xml/" + txtIP.Text;
myHttpWebRequest = (HttpWebRequest)HttpWebRequest.Create(weatherURL);
myHttpWebRequest.Method = "GET";
myHttpWebRequest.ContentType = "text/xml; encoding='utf-8'";
myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
myXMLReader = new XmlTextReader(myHttpWebResponse.GetResponseStream());
docNav = new XPathDocument(myXMLReader);
nav = docNav.CreateNavigator();
nav.MoveToRoot();
nav.MoveToFirstChild();
do
{
if (nav.NodeType == XPathNodeType.Element)
{
nav.MoveToFirstChild();
do
{
txtIPresults.Text = txtIPresults.Text + nav.Name + " - " + nav.Value + Environment.NewLine; //Display
} while (nav.MoveToNext());
}
} while (nav.MoveToNext());
}
catch (Exception myException)
{
throw new Exception("Error Occurred:", myException);
}
finally
{
myHttpWebRequest = null;
myHttpWebResponse = null;
myXMLReader = null;
}
If I understand correctly you are trying to get the values from the countryName and city elements from the XML response.
This can be done in the following way using the XDocument class from the System.Xml.Linq namespace:
HttpWebRequest myHttpWebRequest = null;
HttpWebResponse myHttpWebResponse = null;
try
{
String weatherURL = "http://smart-ip.net/geoip-xml/" + txtIP.Text;
myHttpWebRequest = (HttpWebRequest)HttpWebRequest.Create(weatherURL);
myHttpWebRequest.Method = "GET";
myHttpWebRequest.ContentType = "text/xml; encoding='utf-8'";
myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
//---- <Added code> -------
var doc = XDocument.Load(myHttpWebResponse.GetResponseStream());
var geoip = doc.Element("geoip");
var country = geoip.Element("countryName").Value;
var city = geoip.Element("city").Value;
Console.WriteLine(country + " - " + city);
//---- </Added code> -------
}
catch (Exception myException)
{
throw new Exception("Error Occurred:", myException);
}
finally
{
myHttpWebRequest = null;
myHttpWebResponse = null;
}
It's also possible to use the XDocument.Load() method to load the XML response using the url string directly:
String weatherURL = "http://smart-ip.net/geoip-xml/" + txtIP.Text;
var doc = XDocument.Load(weatherURL);
I would do something like this:
try
{
WebClient wc = new WebClient();
wc.Headers.Add();//ADD ALL YOUR HEADERS IF YOU NEED
var xml = wc.DownloadString(string.Format("http://smart-ip.net/geoip-xml/{0}", txtIP.Text));
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
var name = doc.DocumentElement.SelectSingleNode("//countryName").Value;
txtIPresults.Text = name
}
catch (Exception myException)
{
throw new Exception("Error Occurred:", myException);
}
I donĀ“t know for sure if it have more performance than HTTP REQUEST/RESPONSE but the code is very small and easy to maintain.
This question already has answers here:
How to post JSON to a server using C#?
(15 answers)
Closed 1 year ago.
I am trying to make a json call using C#. I made a stab at creating a call, but it did not work:
public bool SendAnSMSMessage(string message)
{
HttpWebRequest request = (HttpWebRequest)
WebRequest.Create("http://api.pennysms.com/jsonrpc");
request.Method = "POST";
request.ContentType = "application/json";
string json = "{ \"method\": \"send\", "+
" \"params\": [ "+
" \"IPutAGuidHere\", "+
" \"msg#MyCompany.com\", "+
" \"MyTenDigitNumberWasHere\", "+
" \""+message+"\" " +
" ] "+
"}";
StreamWriter writer = new StreamWriter(request.GetRequestStream());
writer.Write(json);
writer.Close();
return true;
}
Any advice on how to make this work would be appreciated.
In your code you don't get the HttpResponse, so you won't see what the server side sends you back.
you need to get the Response similar to the way you get (make) the Request. So
public static bool SendAnSMSMessage(string message)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://api.pennysms.com/jsonrpc");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{ \"method\": \"send\", " +
" \"params\": [ " +
" \"IPutAGuidHere\", " +
" \"msg#MyCompany.com\", " +
" \"MyTenDigitNumberWasHere\", " +
" \"" + message + "\" " +
" ] " +
"}";
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
//Now you have your response.
//or false depending on information in the response
return true;
}
}
I also notice in the pennysms documentation that they expect a content type of "text/json" and not "application/json". That may not make a difference, but it's worth trying in case it doesn't work.
just continuing what #Mulki made with his code
public string WebRequestinJson(string url, string postData)
{
string ret = string.Empty;
StreamWriter requestWriter;
var webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;
if (webRequest != null)
{
webRequest.Method = "POST";
webRequest.ServicePoint.Expect100Continue = false;
webRequest.Timeout = 20000;
webRequest.ContentType = "application/json";
//POST the data.
using (requestWriter = new StreamWriter(webRequest.GetRequestStream()))
{
requestWriter.Write(postData);
}
}
HttpWebResponse resp = (HttpWebResponse)webRequest.GetResponse();
Stream resStream = resp.GetResponseStream();
StreamReader reader = new StreamReader(resStream);
ret = reader.ReadToEnd();
return ret;
}
Here's a variation of Shiv Kumar's answer, using Newtonsoft.Json (aka Json.NET):
public static bool SendAnSMSMessage(string message)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://api.pennysms.com/jsonrpc");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
var serializer = new Newtonsoft.Json.JsonSerializer();
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
using (var tw = new Newtonsoft.Json.JsonTextWriter(streamWriter))
{
serializer.Serialize(tw,
new {method= "send",
#params = new string[]{
"IPutAGuidHere",
"msg#MyCompany.com",
"MyTenDigitNumberWasHere",
message
}});
}
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
//Now you have your response.
//or false depending on information in the response
return true;
}
}
If your function resides in an mvc controller u can use the below code with a dictionary object of what you want to convert to json
Json(someDictionaryObj, JsonRequestBehavior.AllowGet);
Also try and look at system.web.script.serialization.javascriptserializer if you are using .net 3.5
as for your web request...it seems ok at first glance..
I would use something like this..
public void WebRequestinJson(string url, string postData)
{
StreamWriter requestWriter;
var webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;
if (webRequest != null)
{
webRequest.Method = "POST";
webRequest.ServicePoint.Expect100Continue = false;
webRequest.Timeout = 20000;
webRequest.ContentType = "application/json";
//POST the data.
using (requestWriter = new StreamWriter(webRequest.GetRequestStream()))
{
requestWriter.Write(postData);
}
}
}
May be you can make the post and json string a parameter and use this as a generic webrequest method for all calls.
Its just a sample of how to post Json data and get Json data to/from a Rest API in BIDS 2008 using System.Net.WebRequest and without using newtonsoft. This is just a sample code and definitely can be fine tuned (well tested and it works and serves my test purpose like a charm). Its just to give you an Idea. I wanted this thread but couldn't find hence posting this.These were my major sources from where I pulled this.
Link 1 and Link 2
Code that works(unit tested)
//Get Example
var httpWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("https://abc.def.org/testAPI/api/TestFile");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "GET";
var username = "usernameForYourApi";
var password = "passwordForYourApi";
var bytes = Encoding.UTF8.GetBytes(username + ":" + password);
httpWebRequest.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(bytes));
var httpResponse = (System.Net.HttpWebResponse)httpWebRequest.GetResponse();
using (StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
string result = streamReader.ReadToEnd();
Dts.Events.FireInformation(3, "result from readng stream", result, "", 0, ref fireagain);
}
//Post Example
var httpWebRequestPost = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("https://abc.def.org/testAPI/api/TestFile");
httpWebRequestPost.ContentType = "application/json";
httpWebRequestPost.Method = "POST";
bytes = Encoding.UTF8.GetBytes(username + ":" + password);
httpWebRequestPost.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(bytes));
//POST DATA newtonsoft didnt worked with BIDS 2008 in this test package
//json https://stackoverflow.com/questions/6201529/how-do-i-turn-a-c-sharp-object-into-a-json-string-in-net
// fill File model with some test data
CSharpComplexClass fileModel = new CSharpComplexClass();
fileModel.CarrierID = 2;
fileModel.InvoiceFileDate = DateTime.Now;
fileModel.EntryMethodID = EntryMethod.Manual;
fileModel.InvoiceFileStatusID = FileStatus.NeedsReview;
fileModel.CreateUserID = "37f18f01-da45-4d7c-a586-97a0277440ef";
string json = new JavaScriptSerializer().Serialize(fileModel);
Dts.Events.FireInformation(3, "reached json", json, "", 0, ref fireagain);
byte[] byteArray = Encoding.UTF8.GetBytes(json);
httpWebRequestPost.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = httpWebRequestPost.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = httpWebRequestPost.GetResponse();
// Display the status.
//Console.WriteLine(((HttpWebResponse)response).StatusDescription);
Dts.Events.FireInformation(3, "Display the status", ((HttpWebResponse)response).StatusDescription, "", 0, ref fireagain);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
Dts.Events.FireInformation(3, "responseFromServer ", responseFromServer, "", 0, ref fireagain);
References in my test script task inside BIDS 2008(having SP1 and 3.5 framework)