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 am trying to call api using WebRequest, Api method is post following is my code.
string ContactUs = "https://nestiolistings.com/api/v1/clients/" + APIKey;
var request = (HttpWebRequest)WebRequest.Create(ContactUs);
request.Headers.Add("Authorization", "Basic ############");
request.Method = "POST";
request.ContentType = "application/json";
request.Accept = "application/json";
JavaScriptSerializer jss = new JavaScriptSerializer();
List<people> list = new List<people>();
people obj = new people();
obj.first_name = model.Name;
obj.last_name = model.Name;
obj.email = model.Email;
obj.phone_1 = "";
obj.date_of_birth = "";
list.Add(obj);
RequestModel rm = new RequestModel();
rm.people = list;
rm.notes = model.Message;
// string yourdata = jss.Deserialize<UserInputParameters>(stdObj);
string yourdata = jss.Serialize(rm);
StreamWriter requestWriter = new StreamWriter(request.GetRequestStream());
requestWriter.Write(yourdata);
requestWriter.Close();
StreamReader responseReader = new StreamReader(request.GetResponse().GetResponseStream());
string responseData = responseReader.ReadToEnd();
responseReader.Close();
request.GetResponse().Close();
But it gives all time 404 not found error.please some one help.
string ContactUs = "https://nestiolistings.com/api/v1/clients/" + APIKey;
I don't think you should be appending the API key to the URL. Say your key was 12345, you'll end up with a URL like https://nestiolistings.com/api/v1/clients/12345.
That won't map to a valid resource in the API - the "clients" method is for creating clients, for that reason it doesn't accept specific Client IDs as extra route parameters (because the Client doesn't exist yet therefore doesn't have an ID), and even if it did and made logical sense to do so, your API key would, obviously, not match a valid Client ID.
The API Key should be provided in the authorisation header by the looks of it.
So:
string ContactUs = "https://nestiolistings.com/api/v1/clients/";
var request = (HttpWebRequest)WebRequest.Create(ContactUs);
request.Headers.Add("Authorization", "Basic " + APIKey);
(This is assuming that APIKey is already a base64-encoded string as required by the API).
See http://developers.nestio.com/api/v1/clients.html and http://developers.nestio.com/api/v1/auth.html for further information.
Related
I am doing a bit of research into building a program to use the Australian crypto trading platform Coinspot. I have used API's in the past but barley used "POST" method, Coinspots information and documentation is sooooooo poor (probs because they don't want you to use it) but i figured ill give it a whirl anyways.
Question:
How do you use a POST method if you do not know the order in which to send data? (is there a standard or is every API different).
i have an API key and a secret API key to send for authorisation but still get access denied.
Is there anyway you can use code to request an order or something like you do when you pull a json to string?
WebRequest request = WebRequest.Create("https://www.coinspot.com.au/api/ro/balances");
request.Method = "POST";
request.Headers.Add("key", APIKEY);
request.ContentType = "application/json";
request.GetResponse(); //THIS IS WHERE IT ERRORS WITH AUTHENTICATION
sorry if its a scrub question but i think im looking at this the right way, i am also using .NET library json newtonsoft so any information on this would be fantastic!!
.NET Core interpretation of the somewhat dated yet functional CoinSpot node.js api client
var nonce = Utility.GetEpochTime();
var postData = new { nonce };
var jsonMessage = postData.ToJson();
var hmac = new HMACSHA512(Encoding.ASCII.GetBytes("CoinSpotSecret"));
var byteArray = Encoding.ASCII.GetBytes(jsonMessage);
using (var stream = new MemoryStream(byteArray)) {
var hash = hmac.ComputeHash(stream).Aggregate("", (s, e) => s + String.Format("{0:x2}", e), s => s);
var uri = new Uri("https://www.coinspot.com.au/api/ro/my/balances", UriKind.Absolute);
var content = new StringContent(
jsonMessage,
System.Text.Encoding.UTF8,
"application/json"
);
content.Headers.Add("sign", hash);
content.Headers.Add("key", "CoinSpotKey");
var response = await httpClient.PostAsync(uri, content);
if (response.IsSuccessStatusCode) {
return await response.Content.ReadAsStringAsync();
}
}
I'm trying to make a POST call (from a C# WPF app) to a web service on an internal intranet (so I can't give the exact URL sorry), which is basically a url shortening service.
The page gives the following instructions:
In order to use the API service, simply make HTTP POST requests to this URL:
https://...internalAddress.../api/<method>
For example, to create a snip, make an HTTP POST request to:
https://...internalAddress.../api/shorten
with these parameters:
api_key hash of a registered API key
url URL to be shortened
Now I have tried to implement this in a couple of different ways with what I've found via google / here, these are:
1:
string apiKey = "xxxx11112222333";
string urlForShortening = #"http://www.codeproject.com/Tips/497123/How-to-make-REST-requests-with-Csharp";
string destination = #"https://internalurl/api/shorten";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(destination);
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write("{'api_key': '" + apiKey + "', 'url': '" + urlForShortening + "'}");
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
MessageBox.Show(responseText);
}
2: (Using the rest library created in the article found in the shortening link)
string apiKey = "xxxx11112222333";
string urlForShortening = #"http://www.codeproject.com/Tips/497123/How-to-make-REST-requests-with-Csharp";
string destination = #"https://internalurl/api/shorten";
RestClient client = new RestClient(destination, HttpVerb.POST,
"{'api_key': '" + apiKey + "', 'url': '" + urlForShortening + "'}");
var json = client.MakeRequest();
MessageBox.Show(json);
have also tried feeding in the jsonData in double quotes:
var jsonData = "{\"api_key\": \"" + apiKey + "\", \"url\": \"" + urlForShortening + "\"}";
The result from both methods I always get is:
{"status": 400, "message": "Missing API key"}
Can someone please shed some light on what I'm doing wrong?
From the brief, I think the key may need to be hashed in some form and not sure how to do this.
Turns out my whole implementation was wrong, I was trying to send the data as JSON / using the wrong classes instead of a vanilla HTTP POST.
I used Method 2 found in this article and it worked fine: HTTP request with post
ie.
using (var client = new WebClient())
{
var values = new NameValueCollection();
values["api_key"] = "xxxx11112222333";
values["url"] = #"http://www.codeproject.com";
string destination = #"https://internalurl/api/shorten";
var response = client.UploadValues(destination, values);
var responseString = Encoding.Default.GetString(response);
MessageBox.Show(responseString);
}
Thanks for your help though!
I assume that you are attempting to send json data in the request body for the POST call to the API.
You dont seem to be providing a valid json here though. This is what you are sending now:
{'api_key':'someApiKey'}
{'url':'someUrlForShortening'}
Use a json validator to ensure you have a valid json document before you attempt to send it to the API.
A valid json would be
{
"api_key":"someApiKey",
"url":"someUrlForShortening"
}
I have a string with 300 rows, there is a way to do it POST?
Here is my code, is currently working on a limited amount of short letters:
WebRequest req = (HttpWebRequest)WebRequest.Create(
"http://thisisurl/test.php?ad=test&f=" + information_data);
req.Method = "POST";
WebResponse res = req.GetResponse();
I'm going to explain your problem right now and go ahead and give you a possible solution at the end.
You are hitting the character limit for url length / query parameter length. IE limits it as low as 2,083.
The data you are providing should be sent in the body of the http request, not the URL parameters.
A Post Request Normally is done in the following format(Code from the link).
using (var wb = new WebClient())
{
var data = new NameValueCollection();
data["username"] = "myUser";
data["password"] = "myPassword";
var response = wb.UploadValues(url, "POST", data);
}
This thread should have enough info if you want to use the WebRequest class instead:
HTTP request with post
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I'm in the process of creating a C# console application which reads text from a text file, turns it into a JSON formatted string (held in a string variable), and needs to POST the JSON request to a web api. I'm using .NET Framework 4.
My struggle is with creating the request and getting the response, using C#. What is the basic code that is necessary? Comments in the code would be helpful. What I've got so far is the below, but I'm not sure if I'm on the right track.
//POST JSON REQUEST TO API
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("POST URL GOES HERE?");
request.Method = "POST";
request.ContentType = "application/json";
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
byte[] bytes = encoding.GetBytes(jsonPOSTString);
request.ContentLength = bytes.Length;
using (Stream requestStream = request.GetRequestStream())
{
// Send the data.
requestStream.Write(bytes, 0, bytes.Length);
}
//RESPONSE HERE
Have you tried using the WebClient class?
you should be able to use
string result = "";
using (var client = new WebClient())
{
client.Headers[HttpRequestHeader.ContentType] = "application/json";
result = client.UploadString(url, "POST", json);
}
Console.WriteLine(result);
Documentation at
http://msdn.microsoft.com/en-us/library/system.net.webclient%28v=vs.110%29.aspx
http://msdn.microsoft.com/en-us/library/d0d3595k%28v=vs.110%29.aspx
Try using Web API HttpClient
static async Task RunAsync()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://domain.com/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// HTTP POST
var obj = new MyObject() { Str = "MyString"};
response = await client.PostAsJsonAsync("POST URL GOES HERE?", obj );
if (response.IsSuccessStatusCode)
{
response.//.. Contains the returned content.
}
}
}
You can find more details here Web API Clients
I am (trying) to develop a WPF (C#) app that just gets (or at least is supposed to get) my saved bookmarks at Diigo.com profile. The only helpful page i found is this . It says i have to use HTTP Basic authetication to get my self authenticated and make requests then. But don't understand how C# handles it!. The only solution i came up with below just prints entire HTML source to console window.
string url = "http://www.diigo.com/sign-in";
WebRequest myReq = WebRequest.Create(url);
string usernamePassword = "<username>:<password>";
CedentialCache mycache = new CredentialCache();
mycache.Add(new Uri(url), "Basic", new NetworkCredential("username", "password"));
myReq.Credentials = mycache;
myReq.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword)));
//Send and receive the response
WebResponse wr = myReq.GetResponse();
Stream receiveStream = wr.GetResponseStream();
StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
string content = reader.ReadToEnd();
Console.Write(content);
Here username and password are hardcoded but of course they'll come from some txtUsername.Text thing. And after that how am i going to read the JSON response and parse it?
What is that i need to do to get my app or myself HTTP basic authenticated?
Any help or suggestion is welcome!
If you're trying to talk to a service, you probably want to use the Windows Communication Foundation (WCF). It's designed specifically to solve the problems associated with communicating with services, such as reading/writing XML and JSON, as well as negotiating transports mechanisms like HTTP.
Essentially, WCF will save you doing all of the "plumbing" work of working with HttpRequest objects and manipulating strings. Your problems have already been solved by this framework. Use it if you can.
Ok i solved the problem after some (not really some) effort. Code below gets the JSON response from server which can then be parsed using any preferred method.
string key = "diigo api key";
string username = "username";
string pass = "password";
string url = "https://secure.diigo.com/api/v2/";
string requestUrl = url + "bookmarks?key=" + key + "&user=" + username + "&count=5";
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(requestUrl);
string usernamePassword = username + ":" + pass;
myReq.Timeout = 20000;
myReq.UserAgent = "Sample VS2010";
//Use the CredentialCache so we can attach the authentication to the request
CredentialCache mycache = new CredentialCache();
//this perform Basic auth
mycache.Add(new Uri(requestUrl), "Basic", new NetworkCredential(username, pass));
myReq.Credentials = mycache;
myReq.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword)));
//Send and receive the response
WebResponse wr = myReq.GetResponse();
Stream receiveStream = wr.GetResponseStream();
StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
string content = reader.ReadToEnd();
Console.Write(content);
content is the JSON response returned from server
Also this link is useful for getting started with api.