I am working with eloqua 10.
I need to create Email in eloqua by using their rest api from an aspx web page.But am get 404 Bad Request.
Given below is the code sample for the POST request that I tried.
string authenticateStr = eloquainstance + #"\" + username + ':' + password;
byte[] bytesToEncode = Encoding.UTF8.GetBytes(authenticateStr);
string encodedText = Convert.ToBase64String(bytesToEncode);
string requrl = "/assets/email";
string requestBody = "<subject>Test subject</subject>" +
"<senderName>Ajai Test</senderName>" +
"<senderEmail>amani#suyati.com</senderEmail>" +
"<emailGroupId>9</emailGroupId>" +
"<htmlContent>This is a test email templete created trough rest api.This is for testing purpose only</htmlContent>"+
"<type>Email</type>" +
"<name>Email By api</name>";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(baseurl + requrl);
request.Headers.Add("Authorization", "Basic " + encodedText);
request.Accept = "application/xml";//"application/x-www-form-urlencoded";
request.Method = "POST";
request.ContentType = "application/xml";
request.ContentLength = requestBody.Length;
//write body to text
byte[] body = System.Text.Encoding.UTF8.GetBytes(requestBody);
Stream dataStream = request.GetRequestStream();
dataStream.Write(body, 0, requestBody.Length);
dataStream.Close();
HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse();
Please correct me if anything wrong in my code.
Can anybody tried a post using eloqua rest api, if so can you share a sample code to make a POST request to eloqua from c#.Any help be appreciable.
Not sure whether you've got this working yet as some time has passed since you asked this, but you can find a whole set of samples for using eloqua's topliners site:
http://topliners.eloqua.com/community/code_it/blog/2012/10/08/eloqua-rest-api--open-source-c-samples
Looking at your code I think you may need to escape the html body
I would also consider writing a class to represent the email object and then use restsharp to simplify the process of serialising the request and handling the response.
Also experiment with test requests using fiddler.
Related
I am developing console application for API integration. This follow fetching token in first request and then getting report in second request after passing token.
string token = GetToken(app_id); // API call, which is working fine and getting token
string reportquerystring = "path?token=" + token;
WebRequest req = WebRequest.Create(#reportquerystring);
req.Method = "GET";
req.Headers["Authorization"] = "Basic " +
Convert.ToBase64String(Encoding.Default.GetBytes("username:password"));
var resp = req.GetResponse() as HttpWebResponse;
using (Stream downloadstream = resp.GetResponseStream())
{
XmlDocument reportxml = new XmlDocument();
string filename = "location\\";
string reportxmlString = (new StreamReader(downloadstream)).ReadToEnd();
reportxml.LoadXml(reportxmlString);
string json = JsonConvert.SerializeXmlNode(reportxml);
System.IO.File.WriteAllText(filename + "data_" + app_id + ".txt", json);
}
Here when I run this code while debugging, on the first call of download report, response xml is empty, when I drag debugger again before call, in the same run, then it gets response properly. But until and unless I figure out the reason why first call to download report API is not working or how I can make it work, I can not proceed.
Any suggestions ?
I've been working on the Walmart API but I keep getting either the 401 error or the 500 error when I run the code
public void post()
{
byte[] data = Encoding.ASCII.GetBytes(
$"username={user}&password={password}");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://marketplace.walmartapis.com/v2/feeds?feedType=item");
request.Method = "POST";
request.Accept = "application/xml;";
request.ContentLength = data.Length;
request.Headers.Add("WM_SVC.NAME", "Walmart Marketplace");
request.Headers.Add(authId);
request.Headers.Add("WM_CONSUMER.ID", user);
request.Headers.Add( time);
request.Headers.Add(CorId);
using (Stream stream = request.GetRequestStream ())
{
stream.Write(data , 0, data.Length);
}
string responseContent = null;
using (WebResponse response = request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
using (StreamReader sr99 = new StreamReader(stream))
{
responseContent = sr99.ReadToEnd();
}
}
}
MessageBox.Show(responseContent);
}
where authID is a signature generated from a jar file provided by walmart
time is also generated from the jar file
CorID is a randomly generated number
and user is the user id.
here is the link that describes the header parameters. Did I miss something in my header?
https://developer.walmartapis.com/#getting-started
There are multiple problems with your request. First, you are submitting a feed, but sending it as an application/xml when it should be a multipart/form-data request. Beyond this, your headers aren't set up properly and there is currently a major problem with submitting multipart/form-data requests to Walmart using C#. I have not seen a post from anyone successfully sending a feed to Walmart via C#. I am currently using C# to execute a batch file that then fires a modified version of the Walmart Java SDK which is capable of sending the multipart/form-data requests.
The reponse below is for any request other than feeds. I would start with the example listed below to get familiar with how you need to set your headers up. This is going to work for the majority of Walmart interfacing, but if the request is a feed style request, you will either need to come up with a better solution to the multipart/form-data issue, use the Java SDK, or wait for the C# SDK. If someone reads this and has a better answer as to how to submit feeds via C# exclusively I would love to hear about it!
Here is an example of an application/xml request that works.
string timestamp = CurrentTimeMillis().ToString().Trim();
string query = #"orders/"+poID+"/acknowledge";
string request = v3BaseUrl + query; //Constructed URI
string stringToSign = consumerId + "\n" +
request.Trim() + "\n" +
"POST" + "\n" +
timestamp + "\n";
string signedString = signData(stringToSign); //Your signed string
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(request);
webRequest.Accept = "application/xml";
webRequest.ContentType = "application/xml";
webRequest.Method = "POST";
webRequest.Headers.Add("WM_SVC.NAME", "Walmart Marketplace");
webRequest.Headers.Add("WM_SEC.AUTH_SIGNATURE", signedString);
webRequest.Headers.Add("WM_CONSUMER.ID", consumerId);
webRequest.Headers.Add("WM_SEC.TIMESTAMP", timestamp.ToString().Trim());
webRequest.Headers.Add("WM_QOS.CORRELATION_ID", Guid.NewGuid().ToString());
webRequest.Headers.Add("WM_CONSUMER.CHANNEL.TYPE", channelType);
webRequest.ContentLength = 0;
webRequest.Timeout = Timeout.Infinite;
webRequest.KeepAlive = true;
using (HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse())
{
if (response.StatusCode == HttpStatusCode.OK)
{
success = true;
}
}
I am developing ASP.net application which consumes REST services with ASP.Net Web API. I am trying to use Basic authentication for my website. I plan to use it with SSL once I complete Basic authentication.
Currently on Login button click I am sending Auth header using Base64 encoding of username and password as shown below:
string responseData = string.Empty;
string authToken = string.Empty;
string loginInstance = url;
// Create request.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(loginInstance);
request.Method = "POST";
request.ContentType = "application/json";
request.CookieContainer = new CookieContainer();
String username = txtUserName.Text;
String password = txtPassword.Text;
String encoded = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(username + ":" + password));
request.Headers.Add("Authorization", "Basic " + encoded);
request.ContentLength = 0;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8);
String resultData = reader.ReadToEnd();
bool result = false;
result = Convert.ToBoolean(resultData);
return result;
I assume I will need to send authentication header to all of those web api requests that needs to be secure and pass through authentciation.
Is there a way to attach authentication header to every request that I send or even to a set of requests?
Please note: most of the Web API requests are invoked through JQuery.
Also please let me know if this is not recommended approach of implementation.
Regards,
Abhilash
Have you try like this :
WebRequest request = (HttpWebRequest)WebRequest.Create("https://yoururl");
request.Headers.Add(HttpRequestHeader.Authorization, "Basic " + Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes("user:password")));
basic http authentication in asp.net web api using message handlers.
http://www.piotrwalat.net/basic-http-authentication-in-asp-net-web-api-using-message-handlers/
Can you try with below code inplace of "request.Headers.Add("Authorization", "Basic " + encoded);" .
request.Headers.Add(HttpRequestHeader.Authorization, "Basic " +
Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes("user:password")));
I believe you can just add
request.PreAuthenticare = true
You may look for HttpWebRequest.Credentials Property.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(loginInstance);
request.Credentials = CredentialCache.DefaultCredentials;
Above example contains the credentials of the currently logged on user.
"The Credentials property can be either a NetworkCredential, in which case the user, password, and domain information contained in the NetworkCredential object is used to authenticate the request, or it can be a CredentialCache".
MSDN Reference
I am trying follow the example given at AWS documentation Signing AWS requests and make a ListUsers call in C#. I have arrived till the last stage of generating the signature (i.e ready to submit the signed request given at signature-4 request examples). But the code I pasted below is throwing 'bad request' exception when submitted.
static void submitSignedRequest(string my_access_key, string my_secret_key, string signature, string curr_utc_date_string, string curr_utc_datetime_string)
{
string url = "https://iam.amazonaws.com/?Action=ListUsers&Version=2010-05-08&X-Amz-Algorithm=AWS4-HMAC-SHA256&" +
"X-Amz-Credential=" + my_access_key + "/" + curr_utc_date_string + "/us-east-1/iam/aws4_request&X-Amz-Date=" + curr_utc_datetime_string +
"&X-Amz-SignedHeaders=content-type;host;x-amz-date&X-Amz-Signature=" + signature;
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "POST";
request.Host = "iam.amazonaws.com";
request.ContentType = "application/x-www-form-urlencoded; charset=utf-8";
WebHeaderCollection headers = (request as HttpWebRequest).Headers;
headers.Add("Authorization", "AWS4-HMAC-SHA256 Credential=" + my_access_key +"/" + curr_utc_date_string + "/us-east-1/iam/aws4_request, " +
"SignedHeaders=content-type;host;x-amz-date, Signature=" + signature);
headers.Add("x-amz-date", curr_utc_datetime_string);
HttpWebResponse response;
try
{
response = request.GetResponse() as HttpWebResponse;
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
}
}
Output i get is:
Error Message: The remote server returned an error: (400) Bad Request.
Can some one help me what wrong I am doing here?
Edit:
I solved this finally by myself. I had to transform it to below. (answer is for RDS though I believe it's visible what the differences are).
string url = "https://rds.us-west-1.amazonaws.com";
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
// ASCIIEncoding encoding = new ASCIIEncoding();
string postData = "Action=DescribeDBInstances&Version=2013-09-09";
byte[] data = Encoding.UTF8.GetBytes(postData);
request.Method = "POST";
request.Host = "rds.us-west-1.amazonaws.com";
request.ContentType = "application/x-www-form-urlencoded; charset=utf-8";
// request.ContentLength = data.Length;
using (Stream stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
WebHeaderCollection headers = (request as HttpWebRequest).Headers;
request.Headers.Add("Authorization", "AWS4-HMAC-SHA256 Credential=" + my_access_key + "/" + curr_utc_date_string + "/us-west-1/rds/aws4_request, " +
"SignedHeaders=content-type;host;x-amz-date, Signature=" + signature);
request.Headers.Add("x-amz-date", curr_utc_datetime_string);
Can some one help me what wrong I am doing here?
Maybe, but I strongly suggest to skip this endeavor all together and just use the excellent AWS SDK for .NET for all your AWS API interactions instead, because it indeed helps take the complexity out of coding by providing .NET APIs for many AWS services including Amazon S3, Amazon EC2, DynamoDB and more.
I'm working with AWS for years in various environments and with all sorts of languages, and I have never even bothered to look into using their API without the assistance of one of the multitude of SDKs they are offering, most of which offer high level tooling in addition to making working with the API from your respective language much easier in the first place.
But if you really need or want to do it yourself, I suggest to simply take a look at the source code of these very SDKs, which are all available at GitHub, including the one for the AWS SDK for .NET - regarding the issue at hand, you might want to start looking into AWS4Signer.cs for example.
Please note that AWS has just released the significantly overhauled version 2, see GA Release of AWS SDK for .NET Version 2 for details.
I'm Trying to access Google Data (Contact, Edit profile data, Calendar ... etc) by using GData and OAuth2.0 server side (Check this link), I finished the first step and got the first code, and when try to post a request to get the oauth2_token I always got the error "The remote server returned an error: (400) Bad Request."
Here is the code I use to POST the request that returns the OAuth2_token:
string clientToken = Request.QueryString["code"];
string post =
string.Format(
#"code={0}&client_id={1}&client_secret={2}&redirect_uri=http://localhost/default.aspx&grant_type=authorization_code",
clientToken, Settings.ClientId, Settings.ClientSecret);
WebRequest httpRequest = WebRequest.Create("https://accounts.google.com/o/oauth2/token");
httpRequest.Method = "POST";
httpRequest.ContentType = "application/x-www-form-urlencoded";
StreamWriter streamWriter = new StreamWriter(httpRequest.GetRequestStream());
streamWriter.Write(post);
streamWriter.Flush();
streamWriter.Close();
var ss = (HttpWebResponse)httpRequest.GetResponse();
Stream stream = ss.GetResponseStream();
Any help??? I spent 2 days till now trying to solve it but in vain :(
could it be that the redirect_uri needs to be URI encoded?
[https://groups.google.com/forum/#!topic/oauth2-dev/9xnn8nUIA2s]
I think you should encode the redirect_uri parameter using HttpUtility.UrlEncode.
also, you should encode the request body using Utf8 encoding:
byte[] encoded = Encoding.UTF8.GetBytes(post);
httpRequest.ContentLength = encoded.Length
hope this helps.