please, help me with POST api request in C#.I dont know how to correctly send parameters „key“, „signature“ and „nonce“ in POST request. It constantly tells me "Missing key, signature and nonce parameters“.
HttpWebRequest webRequest =(HttpWebRequest)System.Net.WebRequest.Create("https://www.bitstamp.net/api/balance/");
if (webRequest != null)
{
webRequest.Method = HttpMethod.Post;
webRequest.ContentType = "application/json";
webRequest.UserAgent = "BitstampBot";
byte[] data = Convert.FromBase64String(apisecret);
string nonce = GetNonce().ToString();
var prehash = nonce + custID + apikey;
string signature = HashString(prehash, data);
body = Serialize(new
{
key=apikey,
signature=signature,
nonce=nonce
});
if (!string.IsNullOrEmpty(body))
{
var data1 = Encoding.UTF8.GetBytes(body);
webRequest.ContentLength = data1.Length;
using (var stream = webRequest.GetRequestStream()) stream.Write(data1, 0, data1.Length);
}
using (Stream s = webRequest.GetResponse().GetResponseStream())
{
using (StreamReader sr = new System.IO.StreamReader(s))
{
contentBody = await sr.ReadToEndAsync();
return contentBody;
}
}
}
The "Request parameters" as Bitstamp specifies in the docs is actually supposed to be sent with content type "application/x-www-form-urlencoded" instead of "application/json".
I would also use HttpClient to perform the post as that has a much more simple setup to perform Http requests
using (var client = new HttpClient())
{
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("key", apikey),
new KeyValuePair<string, string>("signature", signature),
new KeyValuePair<string, string>("nonce", nonce)
});
var result = await client.PostAsync("https://www.bitstamp.net/api/balance/", content);
string resultContent = await result.Content.ReadAsStringAsync();
}
Related
Lately I’ve been experimenting with Xamarin trying to build an android app. I’ve also set up a database (MongoDB) with a node webservice. The user data will be stored in there.
Now, I've a login page and was trying to make a connection with the webservice. The connections do work but when I want to test my login page it always says wrong password/user. Whether I type something in or not it always says the same.
Response: {"message": "Wrong password.", "success": false}
Here's my code:
public class MainActivity : Activity
{
EditText txtMail, txtPwd;
Button buttonSignIn;
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
SetContentView (Resource.Layout.Main);
txtMail = FindViewById<EditText>(Resource.Id.editTxtMail);
txtPwd = FindViewById<EditText>(Resource.Id.editTxtPwd);
buttonSignIn = FindViewById<Button>(Resource.Id.btn_SignIn);
buttonSignIn.Click += async (sender, e) => {
string url = "localhost:3000/login";
JsonValue json = await FetchLoginAsync (url);
};
}
private async Task<JsonValue> FetchLoginAsync (string url)
{
var request = WebRequest.Create(url) as HttpWebRequest;
/*
string auth = "Basic " + Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(txtMail + ":" + txtPwd));
request.PreAuthenticate = true;
request.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested;
request.Headers.Add("Authorization", auth);*/
request.Method = "POST";
request.Headers.Add("email", txtMail.Text);
request.Headers.Add("password", txtPwd.Text);
request.ContentType = "application/x-www-form-urlencoded";
HttpWebResponse Httpresponse = (HttpWebResponse)request.GetResponse();
using (WebResponse response = await request.GetResponseAsync ())
{
using (Stream stream = response.GetResponseStream ())
{
JsonValue jsonDoc = await Task.Run (() => JsonObject.Load (stream));
Console.Out.WriteLine("Response: {0}", jsonDoc.ToString ());
return jsonDoc;
}
}
}
}
I also tried the piece of code I put in comment. But that also not works (and I believe that's not the right way to do it).
I’m new to this, maybe it’s something obvious that I did wrong or totally misunderstood something. Can someone please help me out of this? I’ve been stuck for 2 days already.
Thanks in Advance! :)
you can post parameters through body like this:
using (var client = new HttpClient(new NativeMessageHandler()) { BaseAddress = new Uri(Settings.TokenUrl) })
{
var formContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("grant_type", "refresh_token"),
new KeyValuePair<string, string>("refresh_token", Settings.RefreshToken),
new KeyValuePair<string, string>("client_id", Settings.ClientId),
new KeyValuePair<string, string>("client_secret", Settings.ClientSecret)
});
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.PostAsync(client.BaseAddress, formContent);
if (response.StatusCode == HttpStatusCode.OK)
{
var jsonResult = await response.Content.ReadAsStringAsync();
var json = JObject.Parse(jsonResult);
Settings.RefreshToken = json["refresh_token"].ToString();
Settings.AccessToken = json["access_token"].ToString();
}
}
I've solved my problem like this:
buttonSignIn.Click += delegate {
var request = (HttpWebRequest)WebRequest.Create( LOCALHOST + "login");
var postData = "email=" + txtMail.Text;
postData += "&password=" + txtPwd.Text;
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
I want to send a http post request and capture the response. I have written following code.
System.Net.WebRequest req = System.Net.WebRequest.Create(URI);
req.Proxy = new System.Net.WebProxy(ProxyString, true);
//Add these, as we're doing a POST
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
//We need to count how many bytes we're sending.
//Post'ed Faked Forms should be name=value&
byte [] bytes = System.Text.Encoding.ASCII.GetBytes(Parameters);
req.ContentLength = bytes.Length;
System.IO.Stream os = req.GetRequestStream ();
os.Write (bytes, 0, bytes.Length); //Push it out there
os.Close ();
System.Net.WebResponse resp = req.GetResponse();
if (resp== null) return null;
System.IO.StreamReader sr =
new System.IO.StreamReader(resp.GetResponseStream());
return sr.ReadToEnd().Trim();
Update 1:
I tried making use of PostAsync method. Still the same result.
public static async void Req()
{
using (var client = new HttpClient())
{
var values = new Dictionary<string, string>
{
{ "type1", "val1" },
{ "type2", "val2" },
{ "type3", "val3"}
};
var content = new FormUrlEncodedContent(values);
var r1 = await client.PostAsync(URL, content);
var responseString = await r1.Content.ReadAsStringAsync();
Console.WriteLine(responseString);
Console.ReadLine();
}
}
But its capturing only partial response. My Page takes 10-12 seconds to load. How do I make my script wait and capture complete response?
This could be due to that the response is encoded in som other encoding then UTF8 that StreamReader defaults to. Please check the encoding of the response and alter the call to streamreader from
new System.IO.StreamReader(resp.GetResponseStream());
to
new System.IO.StreamReader(resp.GetResponseStream(), Encoding.ASCII);
for ASCII encoding
working code. Just pass the correct parameters to the method.
public static async void Req()
{
using (var client = new HttpClient())
{
var values = new Dictionary<string, string>
{
{ "type1", "val1" },
{ "type2", "val2" },
{ "type3", "val3"}
};
var content = new FormUrlEncodedContent(values);
var r1 = await client.PostAsync(URL, content);
var responseString = await r1.Content.ReadAsStringAsync();
Console.WriteLine(responseString);
Console.ReadLine();
}
}
}
I am using php REST API and C# to post an image along with access token by using RestSharp, sending image file and access token as parameters but i unable to achieve with this below sample program
private static void postPrescription(string ext, string mime, string token)
{
var restClient = new RestClient("http://api.xxy.in/v1/docsupload");
restClient.AddHandler("application/octet-stream", new RestSharp.Deserializers.JsonDeserializer());
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddHeader("client-Identifier", "192.168.1.24");
request.AddHeader("client-Platform", "kiosk");
request.AddHeader("client-Version", "2.00");
request.AddHeader("client-Type", "kiosk");
request.AddHeader("Accept", "application/json");
Dictionary<string, object> dict = new Dictionary<string, object>();
dict.Add("FILE_EXT", ext);
dict.Add("FILE_MIME_TYPE", mime);
byte[] imageBytes;
using (FileStream fs = File.Open(#"C:\Prescriptions\Presc_1_10_2015_17_19_17.jpeg", FileMode.Open))
{
imageBytes = new BinaryReader(fs).ReadBytes((int)fs.Length);
}
string image = Convert.ToBase64String(imageBytes);
dict.Add("IMAGE_DATA", image);
byte[] data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(dict));
request.AddParameter("access_token", token);
request.AddParameter("userfile", data);
var response = restClient.Execute(request);
JavaScriptSerializer json = new JavaScriptSerializer();
Dictionary<string, object> dict1 = json.Deserialize<Dictionary<string, object>>(response.Content);
}
While trying with above snippet i got a response as
"{\"response\":400,\"message\":\"File not supported\"}"
After this I tried using HTTP POST method but not succeeded, i got http response as "{\"response\":401,\"message\":\"You have been logged out to protect your privacy. Please log back in.\"}"
This is my second snippet,
public static void prescriptionPost(string token)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://api.xxy.in/v1/docsupload");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
httpWebRequestHeaders(httpWebRequest);
httpWebRequest.ContentType = "application/octet-stream";
byte[] imageBytes;
using (FileStream fs = File.Open(#"C:\Prescriptions\Presc_1_10_2015_17_19_17.jpeg", FileMode.Open))
{
imageBytes = new BinaryReader(fs).ReadBytes((int)fs.Length);
}
string image = Convert.ToBase64String(imageBytes);
byte[] data = Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(image));
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
pres ps = new pres
{
access_token = token,
userfile = image
};
string json = Newtonsoft.Json.JsonConvert.SerializeObject(ps, Newtonsoft.Json.Formatting.Indented);
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
StringBuilder output = new StringBuilder();
var result = streamReader.ReadToEnd();
var serializer = new JavaScriptSerializer();
var myobj = serializer.Deserialize<ObtainToken>(result);
}
// example deserializedProduct = Newtonsoft.Json.JsonConvert.DeserializeObject<example>(json);
}
internal class pres
{
public string access_token { get; set; }
public string userfile { get; set; }
}
I dont know whether my snippets are correct or there was a problem exists in RestApi
Can anyone suggest me that how can i achieve this.
using RestSharp;
byte[] imgdata = ImageFileToByteArray(#"D:\SampleIMG.jpg");
RestRequest request = new RestRequest("URL", Method.POST);
request.AddParameter("secret_key", "secret_key_data");
request.AddParameter("Name_Key","Mahesh");
request.AddFile("imageKey", imgdata, "SampleIMG.jpg", "image/jpeg");
RestClient restClient = new RestClient();
IRestResponse response = restClient.Execute(request);
I am new to MVC and C#, so sorry if this question seems too basic.
For a HttpPost Controller like below, how do to call this method directly from a client-side program written in C#, without a browser (NOT from a UI form in a browser with a submit button)? I am using .NET 4 and MVC 4.
I am sure the answer is somehwere on the web, but haven't found one so far. Any help is appreciated!
[HttpPost]
public Boolean PostDataToDB(int n, string s)
{
//validate and write to database
return false;
}
For example with this code in the server side:
[HttpPost]
public Boolean PostDataToDB(int n, string s)
{
//validate and write to database
return false;
}
You can use different approches:
With WebClient:
using (var wb = new WebClient())
{
var data = new NameValueCollection();
data["n"] = "42";
data["s"] = "string value";
var response = wb.UploadValues("http://www.example.org/receiver.aspx", "POST", data);
}
With HttpRequest:
var request = (HttpWebRequest)WebRequest.Create("http://www.example.org/receiver.aspx");
var postData = "n=42&s=string value";
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
With HttpClient:
using (var client = new HttpClient())
{
var values = new List<KeyValuePair<string, string>>();
values.Add(new KeyValuePair<string, string>("n", "42"));
values.Add(new KeyValuePair<string, string>("s", "string value"));
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("http://www.example.org/receiver.aspx", content);
var responseString = await response.Content.ReadAsStringAsync();
}
With WebRequest
WebRequest request = WebRequest.Create ("http://www.example.org/receiver.aspx");
request.Method = "POST";
string postData = "n=42&s=string value";
byte[] byteArray = Encoding.UTF8.GetBytes (postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream ();
dataStream.Write (byteArray, 0, byteArray.Length);
dataStream.Close ();
//Response
WebResponse response = request.GetResponse ();
Console.WriteLine (((HttpWebResponse)response).StatusDescription);
dataStream = response.GetResponseStream ();
StreamReader reader = new StreamReader (dataStream);
string responseFromServer = reader.ReadToEnd ();
Console.WriteLine (responseFromServer);
reader.Close ();
dataStream.Close ();
response.Close ();
see msdn
You can use
First of all you should return valid resutl:
[HttpPost]
public ActionResult PostDataToDB(int n, string s)
{
//validate and write to database
return Json(false);
}
After it you can use HttpClient class from Web Api client libraries NuGet package:
public async bool CallMethod()
{
var rootUrl = "http:...";
bool result;
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(_rootUrl);
var response= await client.PostAsJsonAsync(methodUrl, new {n = 10, s = "some string"});
result = await response.Content.ReadAsAsync<bool>();
}
return result;
}
You can also use WebClient class:
[HttpPost]
public Boolean PostDataToDB(int n, string s)
{
//validate and write to database
return false;
}
public async bool CallMethod()
{
var rootUrl = "http:...";
bool result;
using (var client = new WebClient())
{
var col = new NameValueCollection();
col.Add("n", "1");
col.Add("s", "2");
var res = await client.UploadValuesAsync(address, col);
string res = Encoding.UTF8.GetString(res);
result = bool.Parse(res);
}
return result;
}
If you decide to use HttpClient implementation. Do not create and dispose of HttpClient for each call to the API. Instead, re-use a single instance of HttpClient. You can achieve that declaring the instance static or implementing a singleton pattern.
Reference: https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/
How to implement singleton (good starting point, read the comments on that post): https://codereview.stackexchange.com/questions/149805/implementation-of-a-singleton-httpclient-with-generic-methods
Hopefully below code will help you
[ActionName("Check")]
public async System.Threading.Tasks.Task<bool> CheckPost(HttpRequestMessage request)
{
string body = await request.Content.ReadAsStringAsync();
return true;
}
The gitWebRequest.GetResponse() line is returning a 403 error from the server and I can't seem to figure out why. Any help appreciated.
var address = new Uri(verifyUrl + _apiKey);
HttpRequest request = HttpContext.Current.Request;
var gitWebRequest = WebRequest.Create(address) as HttpWebRequest;
gitWebRequest.Method = "POST";
gitWebRequest.ContentType = "application/json";
var requestReader = new StreamReader(request.InputStream);
var requestBody = requestReader.ReadToEnd();
var myRequestUri = string.Format("{0}://{1}{2}",request.Url.Scheme,request.Url.Authority.TrimEnd('/'), request.RawUrl);
var verifyRequestData = new { requestUri = myRequestUri, postBody = requestBody };
var gitRequestData = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(verifyRequestData));
using (var stream = gitWebRequest.GetRequestStream())
{
stream.Write(gitRequestData, 0, gitRequestData.Length);
}
using (var response = gitWebRequest.GetResponse() as HttpWebResponse)
{
// Get the response stream
if (response != null)
{
var responseReader = new StreamReader(response.GetResponseStream());
result = responseReader.ReadToEnd();
}
}
It was using http instead of https, which is what goole requires.
Thanks for making me look at the url.