How can I post something like this? - c#

I have a problem with the API in a console. So I want to post and I always get 411 error or 403.
This is my code:
string IntId = "suli";
var lekeres = WebRequest.Create("https://xxxx.e-kreta.hu/idp/api/v1/Token") as HttpWebRequest;
lekeres.Method = "POST";
string adatokkal = "institute_code=" + IntId + "&userName=" + azonosito + "&password=" + jelszo + "&grant_type=password&client_id=919e0c1c-76a2-4646-a2fb-7085bbbf3c56";
lekeres.Headers.Add(HttpRequestHeader.Authorization,adatokkal);
var response = lekeres.GetResponse() as HttpWebResponse;
if (response.StatusCode == HttpStatusCode.OK)
{
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
Console.WriteLine(responseFromServer);
}
The origin Curl command (It works):
curl --data "institute_code=xxxxxxxxx&userName=xxxxxxxxxxx&password=xxxxxxxxxxx&grant_type=password&client_id=919e0c1c-76a2-4646-a2fb-7085bbbf3c56" https://xxxxxxxxxxx.e-kreta.hu/idp/api/v1/Token
Thanks for your help!

You could always just use a Webclient:
using (WebClient client = new WebClient())
{
string adatokkal = "https://xxxx.e-kreta.hu/idp/api/v1/Token?institute_code=" + IntId + "&userName=" + azonosito + "&password=" + jelszo + "&grant_type=password&client_id=919e0c1c-76a2-4646-a2fb-7085bbbf3c56";
string Response = client.DownloadString(new Uri(AH_Data_Url));
}
Or a HTTP client
var client = new HttpClient
{
BaseAddress = new Uri("https://xxxx.e-kreta.hu")
};
var request = new HttpRequestMessage(HttpMethod.Post, "/idp/api/v1/Token");
var formData = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("institute_code", IntId )
new KeyValuePair<string, string>("userName", azonosito )
// Add the rest here
};
request.Content = new FormUrlEncodedContent(formData);
var response = client.SendAsync(request).Result;
if (response.IsSuccessStatusCode == true)
{
var responseContent = response.Content;
string responsestring = responseContent.ReadAsStringAsync().Result;
}
else
{
}
If you have to authorize your request you should add something like
var byteArray = new UTF8Encoding().GetBytes("Client ID" + ":" + "Client Secret");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));

Since your curl -d (just a simple POST) works, you need to write your data to the request body, not the Authorization header as you have it. I think this should do it:
string IntId = "suli";
var lekeres = WebRequest.Create("https://xxxx.e-kreta.hu/idp/api/v1/Token") as HttpWebRequest;
lekeres.Method = "POST";
string adatokkal = "institute_code=" + IntId + "&userName=" + azonosito + "&password=" + jelszo + "&grant_type=password&client_id=919e0c1c-76a2-4646-a2fb-7085bbbf3c56";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
lekeres.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
lekeres.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = lekeres.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
var response = lekeres.GetResponse() as HttpWebResponse;
if (response.StatusCode == HttpStatusCode.OK)
{
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
Console.WriteLine(responseFromServer);
}

Related

Basic Authentication with multiple request header in HttpwebRequest in c#. Getting error 401 unauthorized

Getting 401 unauthorized error on calling external API from a console application.
through hhtpwebrequest class. Below is my code... requestBody gives me Json data to post
Please suggest to me how to do authentication.
public string InvokeRestService()
{
var serviceUrl = "http://xrmd0/api/v1.0/student/specialized/feed";
var reqData = _service.Retrieve("entityname",
new Guid("guid"), new ColumnSet("requestdata"));
var requestBody = reqData.Attributes["requestdata"].ToString();
string prefix = #"abc""";
string userName = prefix + "xyz";
string password = "pwdqawe";
try
{
var request = (HttpWebRequest)WebRequest.Create(new Uri(serviceUrl));
request.Method = "POST";
request.ContentType = "application/json";
request.Accept = "application/json";
//request.Headers["authorization"] = "Basic" + Convert.ToBase64String(Encoding.Default.GetBytes(userName + ":" + password));
request.Headers["Authorization"] = "Basic Auth" + Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(userName + ":" + password));
request.Headers["User-Id"] = "userId";
request.Headers["User-Type"] = "usertype";
if (!string.IsNullOrEmpty(requestBody))
{
byte[] data = Encoding.UTF8.GetBytes(requestBody);
var requestStream = request.GetRequestStream();
requestStream.Write(data, 0, data.Length);
requestStream.Close();
}
var response = (HttpWebResponse)request.GetResponse();
var responseStream = response.GetResponseStream();
var responseStreamReader = new StreamReader(responseStream, Encoding.UTF8);
var responseString = responseStreamReader.ReadToEnd();
responseStreamReader.Close();
return responseString;
}
catch (Exception ex)
{
}
}

Invalid Client Authorization header when trying to get token from "Here" REST API

I am trying to get a Bearer token to start using HERE REST API,
using (OAuth 2.0 (JSON Web Tokens))
after a lot of struggles, I am stuck with 401202 error:
{"errorId":"ERROR-e0242f30-05da-4df0-9beb-b697062240ce","httpStatus":401,"errorCode":401202,"message":"Invalid
Client Authorization header, expecting signed request
format.","error":"invalid_request","error_description":"errorCode:
'401202'. Invalid Client Authorization header, expecting signed
request format."}
Here is my code:
private void GetToken()
{
try
{
var here_client_id = "b1Ibl7XXXXXXXoZtNKb";
var here_access_key_id = "8DKjlwXXXXXXXXXerGCXPA";
var here_access_key_secret = "tuU-bGMa1ljancfoXXXXXXXXXXXXXXXK8cMlk4o0EGUpS2fmwkAtlltFPDhYQUgytJLL-X_YNIjmdWcOabQ";
var url = "https://account.api.here.com/oauth2/token";
var Parameters = "grant_type=client_credentials&client_id=" + here_client_id + "&oauth_consumer_key=" + here_access_key_secret;
var hmac = new HMACSHA256();
var key = Convert.ToBase64String(hmac.Key);
Guid id = Guid.NewGuid();
// Create a request for the URL.
WebRequest request = WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
var cred = #"OAuth oauth_consumer_key=" + here_access_key_id;
request.Headers.Add("Authorization", cred);
//request.Headers.Add("oauth_consumer_key", here_access_key_id);
request.Headers.Add("oauth_nonce", id.ToString());
request.Headers.Add("oauth_signature_method", "HMAC-SHA256");
request.Headers.Add("oauth_signature", key);
request.Headers.Add("oauth_timestamp", ConvertToUnixTimestamp(DateTime.Now).ToString());
request.Headers.Add("oauth_version", "1.0");
byte[] byteArray = Encoding.UTF8.GetBytes(Parameters);
request.ContentLength = byteArray.Length;
Stream postStream = request.GetRequestStream();
// Add the post data to the web request
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
// Get the response.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// Display the status.
Console.WriteLine(response.StatusDescription);
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
MessageBox.Show(responseFromServer);
// Cleanup the streams and the response.
reader.Close();
dataStream.Close();
response.Close();
}
catch (WebException ex)
{
using (var stream = ex.Response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
//MessageBox.Show(reader.ReadToEnd());
textBox1.Text = reader.ReadToEnd();
}
}
}
This is my first cut and is rough but.
var accessKey = "";
var secret = "";
var url = "https://account.api.here.com/oauth2/token";
var nonce = GetNonce();
var timestamp = GetTimeStamp();
var baseString = #"grant_type=client_credentials&oauth_consumer_key=" + accessKey + "&oauth_nonce=" + nonce + "&oauth_signature_method=HMAC-SHA256&oauth_timestamp=" + timestamp + "&oauth_version=1.0";
var workingString = new List<string>();
foreach (var parameter in baseString.Split('&').ToList())
{
workingString.Add(Uri.EscapeDataString(parameter.Split('=')[0] + "=" + parameter.Split('=')[1].Trim()));
}
var urlEncodeParamaterString = String.Join(Uri.EscapeDataString("&"), workingString.ToArray());
var fullBaseString = $"POST&{Uri.EscapeDataString(url)}&{urlEncodeParamaterString}";
var signature = CreateToken(fullBaseString, (Uri.EscapeDataString(secret) + "&"));
var authHeader = "OAuth oauth_consumer_key=\"" + accessKey + "\",oauth_signature_method=\"HMAC-SHA256\",oauth_timestamp=\"" + timestamp + "\",oauth_nonce=\"" + nonce + "\",oauth_version=\"1.0\",oauth_signature=\"" + Uri.EscapeDataString(signature) + "\"";
using (HttpClient httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Add("Authorization", authHeader);
var response = await httpClient.PostAsync(url, new StringContent($"grant_type={Uri.EscapeDataString("client_credentials")}",
Encoding.UTF8,
"application/x-www-form-urlencoded"));
var responseContent = response.Content.ReadAsStringAsync();
}
The other Methods are
private string GetNonce()
{
var rand = new Random();
var nonce = rand.Next(1000000000);
return nonce.ToString();
}
private string CreateToken(string message, string secret)
{
secret = secret ?? "";
var encoding = new System.Text.ASCIIEncoding();
byte[] keyByte = encoding.GetBytes(secret);
byte[] messageBytes = encoding.GetBytes(message);
using (var hmacsha256 = new HMACSHA256(keyByte))
{
byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
return Convert.ToBase64String(hashmessage);
}
}
private string GetTimeStamp()
{
var ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalSeconds).ToString();
}
At the end I did it without web JSON WEB TOKENS.
According to this API documentation the call was made only with API KEY.
public static string ConvertAddressToCoordinate(string address)
{
try
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
var apikey = "xxxxxxxxxxxxxxxxxxxxx_xxxxxxxxx";
var url = "https://geocoder.ls.hereapi.com/6.2/geocode.json?apiKey=";
var fullurl = url + apikey + "&searchtext=" + address;
// Create a request for the URL.
WebRequest request = WebRequest.Create(fullurl);
request.Method = "GET";
request.ContentType = "application/json";
// Get the response.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// Display the status.
Console.WriteLine(response.StatusDescription);
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
return responseFromServer;
}
catch (WebException ex)
{
return "ERROR " + ex.Message;
}
catch (Exception ex)
{
return "ERROR " + ex.Message;
}
}

Error:MissingRegistration in GCM with asp.net

I have following code which give "Error:MissingRegistration" response from GCM server.
public void SendPushNotification()
{
string stringregIds = null;
List<string> regIDs = _db.Directories.Where(i => i.GCM != null && i.GCM != "").Select(i => i.GCM).ToList();
//Here I add the registrationID that I used in Method #1 to regIDs
stringregIds = string.Join("\",\"", regIDs);
//To Join the values (if ever there are more than 1) with quotes and commas for the Json format below
try
{
string GoogleAppID = "AIzaSyA2Wkdnp__rBokCmyloMFfENchJQb59tX8";
var SENDER_ID = "925760665756";
var value = "Hello";
WebRequest tRequest;
tRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
tRequest.Method = "post";
Request.ContentType = "application/json";
tRequest.Headers.Add(string.Format("Authorization: key={0}", GoogleAppID));
tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));
string postData = "{\"collapse_key\":\"score_update\",\"time_to_live\":108,\"delay_while_idle\":true,\"data\": { \"message\" : " + "\"" + value + "\",\"time\": " + "\"" + System.DateTime.Now.ToString() + "\"},\"registration_ids\":[\"" + stringregIds + "\"]}";
Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
tRequest.ContentLength = byteArray.Length;
Stream dataStream = tRequest.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse tResponse = tRequest.GetResponse();
dataStream = tResponse.GetResponseStream();
StreamReader tReader = new StreamReader(dataStream);
string sResponseFromServer = tReader.ReadToEnd();
TempData["msg1"] = "<script>alert('" + sResponseFromServer + "');</script>";
HttpWebResponse httpResponse = (HttpWebResponse)tResponse;
string statusCode = httpResponse.StatusCode.ToString();
tReader.Close();
dataStream.Close();
tResponse.Close();
}
catch (Exception ex)
{
}
}
But exact string returned by 'postData' posted by Postman or Fiddler gives positive response and notification arrived at device.
What I'm missing in my code please help me.
The postData returns this value which successfully posted by Postman And Fiddler
{"collapse_key":"score_update","time_to_live":108,"delay_while_idle":true,"data": { "message" : "Hello","time": "5/13/2016 5:50:59 PM"},"registration_ids":["cXMf6hkYIrw:APA91bGr-8y2Gy-qzNJ3zjrlf8t-4m9uDib9P0j8GW87bH5jq891-x_7P0qqItzlc_HXh11Arg76lCOcjXPrU9LAgtYLwllH2ySxA0ADSfiz3qPolajjvI3d3zE6Rh77dwRqXn3NnbAm"]}
The problem in your code is in ContentType
Instead of using this:-
Request.ContentType = "application/json";
Use
tRequest.ContentType = "application/json";
It will work
Try This:-
private string SendGCMNotification()
{
try
{
string message = "some test message";
//string tickerText = "example test GCM";
string contentTitle = "content title GCM";
string registration_id = "cXMf6hkYIrw:APA91bGr-8y2Gy-qzNJ3zjrlf8t-4m9uDib9P0j8GW87bH5jq891-x_7P0qqItzlc_HX‌​h11Arg76lCOcjXPrU9LAgtYLwllH2ySxA0ADSfiz3qPolajjvI3d3zE6Rh77dwRqXn3NnbAm";
string postData =
"{ \"registration_ids\": [ \"" + registration_id + "\" ], " +
"\"data\": {\"contentTitle\":\"" + contentTitle + "\", " +
"\"message\": \"" + message + "\"}}";
string GoogleAppID = "AIzaSyA2Wkdnp__rBokCmyloMFfENchJQb59tX8";
WebRequest wRequest;
wRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
wRequest.Method = "POST";
wRequest.ContentType = " application/json;charset=UTF-8";
wRequest.Headers.Add(string.Format("Authorization: key={0}", GoogleAppID));
var bytes = Encoding.UTF8.GetBytes(postData);
wRequest.ContentLength = bytes.Length;
var stream = wRequest.GetRequestStream();
stream.Write(bytes, 0, bytes.Length);
stream.Close();
var wResponse = wRequest.GetResponse();
stream = wResponse.GetResponseStream();
var reader = new StreamReader(stream);
var response = reader.ReadToEnd();
var httpResponse = (HttpWebResponse)wResponse;
var status = httpResponse.StatusCode.ToString();
reader.Close();
stream.Close();
wResponse.Close();
//TODO check status
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return "sent";
}

How to get response from Base CRM API authentication

I am trying to get a response from Base API, but i keep getting "500 Internal Server Error" error. I want to get at least 401 HTTP Response which means that authentication call has failed. Here is a description of using Base API authentication:
http://dev.futuresimple.com/api/authentication
And here is my code:
public string Authenticate()
{
string result = "";
string url = "https://sales.futuresimple.com/api/v1/";
string email = "mail#mail.com";
string password = "pass";
string postData = "email=" + email + "&password=" + password;
HttpWebRequest request = null;
Uri uri = new Uri(url + "authentication.xml");
request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "application/xml";
request.ContentLength = postData.Length;
using (Stream writeStream = request.GetRequestStream())
{
UTF8Encoding encoding = new UTF8Encoding();
byte[] bytes = encoding.GetBytes(postData);
writeStream.Write(bytes, 0, bytes.Length);
writeStream.Close();
}
try
{
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader readStream = new StreamReader(responseStream, Encoding.UTF8))
{
result = readStream.ReadToEnd();
}
}
}
}
catch (WebException ex)
{
ex = ex;
}
return result;
}
You're setting the ContentType to application/xml - this is the type of the request body. The body you're sending (string postData = "email=" + email + "&password=" + password;) is form-encoded instead of xml. Just skipping the line request.ContentType = "application/xml"; should do the trick. Alternatively you can encode your request body as xml.

json call with C# [duplicate]

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)

Categories