I am trying to create a wrapper for:
this mailchimp method using C#.Net
I understand that there are already .Net wrappers available. I am using Mailchimp.Net by Dan Esparza. Method in the wrapper class is giving exception for the api method mentioned above.It is throwing internal server exception (500) which I am not sure why, so I decided to create my own wrapper for the particular method. I have following code:
private void CreateGrouping(string apiKey, string listId,string groupName,string groupValue)
{
string url = "https://us9.api.mailchimp.com/2.0/lists/interest-grouping-add";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
List<string> values = new List<string>();
values.Add(groupValue);
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = new JavaScriptSerializer().Serialize(new
{
apiKey = apiKey,
id = listId,
name = groupName,
type="radio",
groups = values
});
streamWriter.Write(json);
}
var response = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
But on execution of var response = (HttpWebResponse)httpWebRequest.GetResponse(); is throwing same exception - internal server error (500).
It might be that I am passing data in wrong way ? Can someone please help me in finding out what am I missing here ?
As I suspected I was passing the data in wrong way: apiKey has to be apikey (k was in caps)
string json = new JavaScriptSerializer().Serialize(new
{
apikey = apiKey,
id = listId,
name = groupName,
type="radio",
groups = values
});
Other than this, I added:
streamWriter.Flush();
streamWriter.Close();
It might help someone save sometime.
Related
I'm trying to use Coinbase's API to sell crypto currency, and I keep getting 401 errors. The below code works for all of the GET methods I've tried so far, but I can't figure out where I'm going wrong with the POST.
private static string GetWebResponse(string url, string command, string path, string body)
{
var timeStamp = EpochSeconds;
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = command;
request.ContentType = "application/json";
request.Headers.Add("CB-VERSION", VersionDate);
request.Headers.Add("CB-ACCESS-KEY", ApiKey);
request.Headers.Add("CB-ACCESS-SIGN", GetAccessSign(timeStamp, command, path, body));
request.Headers.Add("CB-ACCESS-TIMESTAMP", timeStamp);
if (command == "POST")
{
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(body);
streamWriter.Flush();
streamWriter.Close();
}
}
var response = (HttpWebResponse)request.GetResponse();
using (var reader = new StreamReader(response.GetResponseStream(), Encoding.ASCII))
{
return reader.ReadToEnd();
}
}
private static string GetAccessSign(string timestamp, string command, string path, string body)
{
var hmacKey = Encoding.UTF8.GetBytes(ApiSecret);
string data = timestamp + command + path + body;
using (var signatureStream = new MemoryStream(Encoding.UTF8.GetBytes(data)))
{
return new HMACSHA256(hmacKey).ComputeHash(signatureStream).Aggregate(new StringBuilder(), (sb, b) => sb.AppendFormat("{0:x2}", b), sb => sb.ToString());
}
}
I figure something is wrong with the body of the POST request, but it looks right to me.
EDIT:
I'm going to show how the body is formed for clarification...
var body = JsonConvert.SerializeObject(
new
{
commit = "false",
amount = Math.Round(sellAmount, 8).ToString(),
currency = "BTC",
payment_method = fiatWalletId
});
EDIT 2:
I tried all the same stuff as before, but using RestSharp, and it returns a more specific error:
{\"errors\":[{\"id\":\"authentication_error\",\"message\":\"invalid signature\"}]}
EDIT 3:
This API key is set up for all permissions / scopes, including the ones I need for this request:
wallet:accounts:create
wallet:accounts:delete
wallet:accounts:read
wallet:accounts:update
wallet:addresses:create
wallet:addresses:read
wallet:buys:create
wallet:buys:read
wallet:checkouts:create
wallet:checkouts:read
wallet:contacts:read
wallet:deposits:create
wallet:deposits:read
wallet:notifications:read
wallet:orders:create
wallet:orders:read
wallet:orders:refund
wallet:payment-methods:delete
wallet:payment-methods:limits
wallet:payment-methods:read
wallet:sells:create
wallet:sells:read
wallet:transactions:read
wallet:transactions:request
wallet:transactions:send
wallet:transactions:transfer
wallet:user:email
wallet:user:read
wallet:user:update
wallet:withdrawals:create
wallet:withdrawals:read
The solution for me was that I forgot to put /v2 (/v2 + some path) in the path part of the signature and the signature was bad, the response was misleading though saying unauthorized.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I Have logic App running in Azure that connect to on premise database , i already succesfull to Post data via xamarin forms but now to make the logic apps link more safety i want to create Web Api that handle the post request. And when I am try to test it via postman it keep getting this message
"Message": "The requested resource does not support http method 'POST'."
I already make post code in the Asp.net and I don't know why its said that my Asp.net don't support html method Post ? here is my full Post Source Code
string sUrl = "My Logic Apps Link";
string sContentType = "application/json"; // or application/xml
// POST api/<controller>
public async void Post(string param1, string param2, string param3)
{
JObject oJsonObject = new JObject();
oJsonObject.Add("param1", param1);
oJsonObject.Add("param2", param2);
oJsonObject.Add("param3", param3);
HttpClient oHttpClient = new HttpClient();
var oTaskPostAsync = await oHttpClient.PostAsync(sUrl, new StringContent(oJsonObject.ToString(), Encoding.UTF8, sContentType));
if (oTaskPostAsync.IsSuccessStatusCode)
{
string content = await oTaskPostAsync.Content.ReadAsStringAsync();
content.ToString();
}
}
please review my code and tell me where is my mistake , because when im try this in xamarin.forms it works and here is the postman body request
{
"param1":"value",
"param2":"value",
"param3":"value"
}
i try with get method and its return value with the parameter hard coded
[Route("postdata")]
// GET api/Post
public string Get()
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://xxx-xx.southeastasia.logic.azure.com");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = new JavaScriptSerializer().Serialize(new
{
param1 = "value",
param2 = "value",
param3 = "value"
});
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
return result;
}
}
but i dont know why the post mode always get error message
// GET api/Post
public string Post(string type, string type1, string email )
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://xxxx-xx.southeastasia.logic.azure.com");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = new JavaScriptSerializer().Serialize(new
{
param1 = type,
param2 = type1,
param3 = email
});
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
return result;
}
}
Why that happen ? I'm still very very new in asp.net, can you tell me where is the part that I'm wrong thanks
You need to add the attribute to the action:
[HttpPost]
public async void Post(string param1, string param2, string param3)
And if you sending the parameter via body you need to tell your action:
[HttpPost]
public async void Post([FromBody]YourClass params)
Take a look at this article: https://learn.microsoft.com/en-us/aspnet/web-api/overview/advanced/sending-html-form-data-part-1
I'm trying to create a version in JIRA for a specific project.
I'm able to do the process via Postman by building my requests manually, but it fails with a 404 when creating the version record via .NET.
I'm assuming .NET adds pesky parameters to the request that Postman doesn't do.
The weird thing is that the authentication call works, but the the version creation fails.
Here's the helper I wrote:
public class JIRA
{
private string AuthToken { get; set; }
private const string c_JIRAUrl = "https://org.atlassian.net";
private const string c_LoginUrl = c_JIRAUrl + "/rest/auth/1/session";
private const string c_CreateVersionUrl = c_JIRAUrl + "/rest/api/2/version";
public JIRA()
{
//this works...
var authResponse = ExecuteRequest(c_LoginUrl, "POST", new
{
username = "login",
password = "password"
});
AuthToken = authResponse["session"]["value"].ToString();
}
public void CreateVersion(string name, string projectKey, ProjectEnvironment environment)
{
//lets hardcode the same data I use in Postman for testing purposes...
var createVersionResponse = ExecuteRequest(c_CreateVersionUrl, "POST", new
{
description = "An excellent version",
name = "1.1.2",
archived = false,
released = false,
project = "TEST"
});
}
private JObject ExecuteRequest(string url, string method, object data)
{
HttpWebResponse response;
var jsonDataString = JsonConvert.SerializeObject(data);
byte[] dataBytes = Encoding.Default.GetBytes(jsonDataString);
var responseText = string.Empty;
var wr = (HttpWebRequest)WebRequest.Create(url);
wr.ContentType = "application/json";
if (!string.IsNullOrEmpty(AuthToken))
wr.Headers.Add(HttpRequestHeader.Authorization, $"Bearer {AuthToken}");
wr.Method = method;
wr.ContentLength = dataBytes.Length;
wr.Accept = "application/json";
using (var webStream = wr.GetRequestStream())
{
webStream.Write(dataBytes, 0, dataBytes.Length);
response = (HttpWebResponse)wr.GetResponse();
}
using (var sr = new StreamReader(response.GetResponseStream()))
{
responseText = sr.ReadToEnd();
}
return JObject.Parse(responseText);
}
}
The CreateVersion method always fails with a 404.
As I've said, doing the same (retrieving the token, creating the version) all works in Postman.
Any ideas what's going on ?
Thanks.
Apparently, when retrieving the token (/rest/auth/1/session) the response contains cookies that POSTMAN was sending back in the 2nd request (creating the version). I had to fire up Fiddler to find out it was doing so because its UI was not saying so.
My .NET client was not doing so. When making it do so, it works.
I'm a little miffed that a REST service expects cookies...
I'm receiving a 400 Bad Request error message when posting a pin on Pinterest. It works using Postman, but doesn't work programmatically. Using C#, has anyone been able to successfully post a pin on Pinterest without using the pinsharp wrapper?
private void postPinterest(string messages, string id, string usertoken, string image, string boardname, string username)
{
string link = null;
boardname = boardname.Replace(" ", "-");
string board = username + "/" + boardname;
string url = "https://api.pinterest.com/v1/pins?access_token=" + usertoken;
StringBuilder sb = new StringBuilder();
if (!string.IsNullOrEmpty(board))
sb.Append("&board=" + HttpUtility.UrlEncode(board));
if (!string.IsNullOrEmpty(messages))
sb.Append("¬e=" + HttpUtility.UrlEncode(messages));
if (!string.IsNullOrEmpty(link))
sb.Append("&image_url=" + HttpUtility.UrlEncode(link));
string postdata = sb.ToString().Substring(1);
PostData(url, postdata);
}
private object PostData(string url, string postdata)
{
object json=null;
try
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
// req.Accept = "application/json";
using (var stream = req.GetRequestStream())
{
byte[] bindata = Encoding.ASCII.GetBytes(postdata);
stream.Write(bindata, 0, bindata.Length);
}
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
string response = new StreamReader(resp.GetResponseStream()).ReadToEnd();
json = JsonConvert.DeserializeObject<dynamic>(response);
return json;
}
catch (WebException wex)
{
if (wex.Response != null)
{
using (var errorResponse = (HttpWebResponse)wex.Response)
{
using (var reader = new StreamReader(errorResponse.GetResponseStream()))
{
string error = reader.ReadToEnd();
return json;
}
}
}
}
return json;
}
EDIT:
It doesn't work using the JSON format or x-www-form-urlencoded format.
I changed the content type to application/x-www-form-urlencoded and now I'm receiving the error message below. I receive 400 Bad Request error using JSON format:
"{\n \"message\": \"405: Method Not Allowed\",\n \"type\": \"http\"\n}"
The problem is the the parameter that you are posting.
In the Api i could find board as a parameter but both note and image comes under field parameter which specifies the return type JSON.
As per documentation on this page you can post in this format
https://api.pinterest.com/v1/boards/anapinskywalker/wanderlust/pins/?
access_token=abcde&
limit=2&
fields=id,link,counts,note
So I tried the following and its getting response
https://api.pinterest.com/v1/boards/?access_token="YourTokenWithoutQuotes"&fields=id%2Ccreator
Would suggest you to first test the Api you are hitting putting a breakpoint inside the PostData function and check if the passed url is in the correct format and compare it with Pininterest API Explorer.
As you might have already received authorization code and access token so I am assuming your post function should be working fine.
public string postPinterest(string access_token,string boardname,string note,string image_url)
{
public string pinSharesEndPoint = "https://api.pinterest.com/v1/pins/?access_token={0}";
var requestUrl = String.Format(pinSharesEndPoint, accessToken);
var message = new
{
board = boardname,
note = note,
image_url = image_url
};
var requestJson = new JavaScriptSerializer().Serialize(message);
var client = new WebClient();
var requestHeaders = new NameValueCollection
{
{"Content-Type", "application/json" },
{"x-li-format", "json" }
};
client.Headers.Add(requestHeaders);
var responseJson = client.UploadString(requestUrl, "POST", requestJson);
var response = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(responseJson);
return response;
}
I am trying to call a web service by passing JSON data. The web service accepts the authentication, where we need to pass the username and password to authenticate.
I am sorry guys, I couldn't disclose the URL and the Username.
Below is my method to do the job.
private static void MakeRequest(string url, string user_name)
{
try
{
var webAddr = url;
var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
httpWebRequest.ContentType = "application/json;";
httpWebRequest.Method = "POST";
//password is blank
var credentialBuffer = new UTF8Encoding().GetBytes(user_name + ":" + "");
httpWebRequest.Headers["Authorization"] = "Basic " + Convert.ToBase64String(credentialBuffer);
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"x\":\"true\"}";
streamWriter.Write(json);
streamWriter.Flush();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
catch (Exception ex)
{
throw;
}
}
When I call the method by passing URL and the username, it is returning error as "The remote server returned an error: (422) Unprocessable Entity."
I guess I am not using the proper authentication method.
Please help.
Is "X" valid attribute parameter to update or create your object ? Because when trying to create or update an object with invalid or missing attribute parameters, you will get a 422 Unprocessable Entity response.