How to post json string on some specific url - c#

I want to log amplitude on https://api.amplitude.com/httpapi using the following code:
private void LogAmplitude()
{
using (var client = new WebClient())
{
var url = "https://api.amplitude.com/httpapi";
client.Headers[HttpRequestHeader.ContentType] = "application/json";
var model = new { user_Id = "userId", event_type = "Event" };
var jss = new JavaScriptSerializer();
var data = jss.Serialize(model);
string parameters = "api_key=" + "apiKey" + "&event=" + data;
var response = client.UploadString(url, parameters);
}
}
But when I run this method it gives me 400(bad request) error. I have tried posting the data using postman through following url:
https://api.amplitude.com/httpapi?api_key=apiKey&event={"user_id":"userId","event_type":"test"}
This works totally fine but when I try to post data using the above method it always gives me error. I am not sure what I am doing wrong because I am doing this kind of work for the very first time. So can anybody help?

In the documentation says that you can use GETwith urlencoded parameters.
Try this:
using (var client = new WebClient())
{
var url = "https://api.amplitude.com/httpapi";
client.Headers[HttpRequestHeader.ContentType] = "application/json";
var model = new { user_id = "userId", event_type = "Event" };
var jss = new JavaScriptSerializer();
var data = jss.Serialize(model);
string parameters = "api_key=" + "apiKey" + "&event=" + System.Uri.EscapeDataString(data);
var response = client.DownloadString ($"{url}?{parameters}");
}

Related

C# httpwebrequest is only sending GET requests even when method is set to POST

I'm using Xamarin C# and php to create a simple android app that sends coordinate data to an apache sql database. When I use httpwebrequest to send a POST request to the server php, it sends a GET instead. Even though I set the request type to POST. The strange thing is that other requests that I have used using the exact same code work okay, this one specifically isn't working.
public class gpsGetterScript{
public static double longitude;
public static double latitude;
public static SimpleLocationManager locationManager = new SimpleLocationManager();
public static void startGetLocation()
{
Timer timer = new Timer();
timer.Interval = 6 * 1000;
void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
double lon = locationManager.LastLocation.Longitude;
double lat = locationManager.LastLocation.Latitude;
longitude = lon;
latitude = lat;
Console.WriteLine(lon.ToString());
Console.WriteLine(lat.ToString());
Dictionary<string, string> gpsData = new Dictionary<string, string>();
gpsData.Add("longitude", lon.ToString());
gpsData.Add("latitude", lat.ToString());
gpsData.Add("device_owner", "Test");
var url = "theURL";
var httpRequest = (HttpWebRequest)WebRequest.Create(url);
httpRequest.Method = "POST";
var contentType = "application/json";
//var contentType = "application/x-www-form-urlencoded";
httpRequest.ContentType = contentType;
var data = JsonConvert.SerializeObject(gpsData);
//var data = "longitude=" + lon.ToString() + "&latitude=" + lat.ToString() + "&device_owner=" + "Test";
using (var streamWriter = new StreamWriter(httpRequest.GetRequestStream()))
{
Console.WriteLine(data.ToString());
Console.WriteLine(httpRequest.RequestUri.ToString());
Console.WriteLine(httpRequest.Headers);
Console.WriteLine(httpRequest.Method);
streamWriter.Write(data);
}
var httpResponse = (HttpWebResponse)httpRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
Console.WriteLine(result);
}
}
timer.Elapsed += Timer_Elapsed;
timer.AutoReset = true;
timer.Start();
locationManager.StartLocationUpdates(LocationAccuracy.Balanced, 5, TimeSpan.FromMinutes(.5), TimeSpan.FromSeconds(20));
SimpleLocationLogger.Enabled = true;
}
}
here is one of the httprequests from a related project that does work (same server being used)
public static string sendLoginRequest(string email, string password)
{
var url = "theURL";
var httpRequest = (HttpWebRequest)WebRequest.Create(url);
httpRequest.Method = "POST";
httpRequest.ContentType = "application/x-www-form-urlencoded";
var data = "email=" + email + "&password=" + password;
using (var streamWriter = new StreamWriter(httpRequest.GetRequestStream()))
{
streamWriter.Write(data);
}
var httpResponse = (HttpWebResponse)httpRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
return result;
}
}
I know it is the app sending the wrong request, as when I made the php echo the request type it came back as GET. Strangely, when I use reqbin to make the POST request using the same URL, it works fine. It really is just for some reason the request in C# is not sending a POST. The other question about this was resolved by adding a www. to the api url, but that did not work for me.
UPDATE: 4/20/2022- Here is the php code
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
include_once '../../../Database.php';
include_once '../location_obj.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$database = new Database();
$db = $database->getConnection();
$data = json_decode(file_get_contents("php://input"));
$item = new location_obj($db);
$stmt = $item->InputCoordinates();
$item->longitude = $data->longitude;
$item->latitude = $data->latitude;
$item->device_owner = $data->device_owner;
if ($item->InputCoordinates()) {
echo json_encode(array("message" => "Successfully", "data" => $item, "Request Type" => $_SERVER['REQUEST_METHOD']));
}
else {
echo json_encode(array("error" => "failed! Check your data and try again.", "data" => $item, "Request Type" => $_SERVER['REQUEST_METHOD']));
}
}
else {
echo json_encode(array("error" => "Only the POST method is supported!", "Request Type" => $_SERVER['REQUEST_METHOD']));
}
?>`
I get the error {"error":"Only the POST method is supported!","Request Type":"GET"} but when I use reqbin I get "message": "Successfully", "data": { "longitude": "theLongitude", "latitude": "theLatitude", "device_owner": "Test" }, "Request Type": "POST"
I checked the url that is used using Console.WriteLine(url); , it is the right one.
I fixed it, seems I forgot to add a / at the end of the URL. It was https://example.com/api/v2/location/input instead of https://example.com/api/v2/location/input/

HTTP Post Authentication error

Here is my code
string URL = "https://api.fastspring.com/accounts";
using (var wb = new WebClient())
{
var data = new NameValueCollection();
var contact = new NameValueCollection();
data["contact"] = "first="+FirstName+"&last="+LastName+"&email="+Email+"&company="+Company;
data["language"] = Language;
data["country"] = Country;
var headers = new WebHeaderCollection();
headers["Authorization"] = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes("username:password"));
headers["User-Agent"] = "request";
//headers["Content-Type"] = "application/json";
wb.Headers = headers;
var response = wb.UploadValues(URL, "POST", data);
return (System.Text.Encoding.UTF8.GetString(response)).Split('"')[3];
}
My problem is that i keep on getting a 401 error saying unauthorised. For one, is my authentication syntax correct? also is my entire setup for sending an HTTP request to the server correct?
here are some useful resources about the fastspring api if it would help:
http://docs.fastspring.com/integrating-with-fastspring/fastspring-api/accounts#id-/accounts-Createanaccount
http://docs.fastspring.com/integrating-with-fastspring/fastspring-api

Passing json urlencode via RestSharp

I have this code which I am attempting to use to communicate an API via RestSharp.
const string task = "pay";
const string command_api_token = "9ufks6FjffGplu9HbaN7uq6XXPPVQXBP";
const string merchant_email_on_voguepay = "mymail#mail.com";
Random rnd = new Random();
string refl = DateTime.Now + rnd.Next(0,9999999).ToString();
byte[] hash_target = Encoding.Default.GetBytes(command_api_token + task + merchant_email_on_voguepay + refl);
string hashD = BitConverter.ToString(new SHA512CryptoServiceProvider().ComputeHash(hash_target)).Replace("-", string.Empty).ToUpper();
var keyValues = new Dictionary<string, string>
{
{ "task", "pay"},
{ "merchant", "3333-4444"},
{ "ref",refl},
{ "hash",hashD},
{ "amount", "20"},
{ "seller", "seller#mail.com"},
{ "remarks", "payment"},
};
//serialization using Newtonsoft JSON
string json = JsonConvert.SerializeObject(keyValues);
//url encode the json
var postString = Server.UrlEncode(json);
//calling API with Restsharp
var client = new RestClient("https://voguepay.com/api/");
var request = new RestRequest(Method.POST);
request.AddParameter("json",json);
IRestResponse response = client.Execute(request);
Textbox1.Text = response.Content;
I think the arrangement of my code is not really ok, because I keep getting error message on each move I make.
If I try to post it as it is above, I get
"response":"X006","description":"Invalid hash"...
If try to get "url encode the json" involved in the "calling API with Restsharp", I get error message as
"response":"X001","description":"Invalid Merchant Id"...
I think I am not placing things right, can someone look at my work and point out what could be the issue with this code?
I am using below code for calling API may this one help u.Here i am passing one class object u replace this by Dictionary and try..
public void insertData(OCMDataClass kycinfo, string clientId, string type)
{
try
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(System.Configuration.ConfigurationManager.AppSettings["CBService"]);
string postBody = Newtonsoft.Json.JsonConvert.SerializeObject(kycinfo);
var jsonString = JsonConvert.SerializeObject(kycinfo);
var content = new StringContent(jsonString, System.Text.Encoding.UTF8, "application/json");
var myContent = JsonConvert.SerializeObject(kycinfo);
var buffer = System.Text.Encoding.UTF8.GetBytes(myContent);
var byteContent = new ByteArrayContent(buffer);
var result = client.PostAsync("Bfilvid/api/SvcVId/CreateKYCRepository", content).Result;
if (result.IsSuccessStatusCode)
{
string resultContent = result.Content.ReadAsStringAsync().Result;
}
else
{
string resultContent = result.Content.ReadAsStringAsync().Result;
}
}
}
catch (Exception ex)
{
}

How to Add new product to Woocommerce using c# RestSharp

I try to add new product to Woocommerce using c# RestSharp, but answer from server is:
{"errors":[{"code":"woocommerce_api_authentication_error","message":"oauth_consumer_key parameter mangler"}]}
For adding product i use next code:
public string AddProduct()
{
Method method = Method.POST;
string result = "";
string endpoint = "products";
var client = new RestClient(ApiUrl);
var parameters = new Dictionary<string, string>();
var request = createRequestWithParams(parameters, endpoint, method);
request.RequestFormat = DataFormat.Json;
request.AddJsonBody(new DTO.WCProduct { title = "eeee2", type = "simple", regular_price = "777", description = "Descr" });
AddOAuthparams(ref parameters, method.ToString(), endpoint);
result = client.Execute(request).Content;
return result;
}
Where Method createRequestWithParams is :
private RestRequest createRequestWithParams(Dictionary<string, string> parameters, string res, Method methos)
{
var req = new RestRequest(res, methos);
foreach (var item in parameters)
{
req.AddParameter(item.Key, item.Value);
}
return req;
}`
Where Method AddOAuthparams is :
void AddOAuthparams(ref Dictionary<string, string> parameters, string method, string endpoint)
{
parameters["oauth_consumer_key"] = this.ConsumerKey;
parameters["oauth_timestamp"] =
DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds.ToString();
parameters["oauth_timestamp"] = parameters["oauth_timestamp"].Substring(0, parameters["oauth_timestamp"].IndexOf(",")); //todo fix for . or ,
parameters["oauth_nonce"] = Hash(parameters["oauth_timestamp"]);
parameters["oauth_signature_method"] = "HMAC-SHA256";
parameters["oauth_signature"] = GenerateSignature(parameters, method, endpoint);
}
public string GenerateSignature(Dictionary<string, string> parameters, string method, string endpoint)
{
var baserequesturi = Regex.Replace(HttpUtility.UrlEncode(this.ApiUrl + endpoint), "(%[0-9a-f][0-9a-f])", c => c.Value.ToUpper());
var normalized = NormalizeParameters(parameters);
var signingstring = string.Format("{0}&{1}&{2}", method, baserequesturi,
string.Join("%26", normalized.OrderBy(x => x.Key).ToList().ConvertAll(x => x.Key + "%3D" + x.Value)));
var signature =
Convert.ToBase64String(HashHMAC(Encoding.UTF8.GetBytes(this.ConsumerSecret),
Encoding.UTF8.GetBytes(signingstring)));
Console.WriteLine(signature);
return signature;
}
private Dictionary<string, string> NormalizeParameters(Dictionary<string, string> parameters)
{
var result = new Dictionary<string, string>();
foreach (var pair in parameters)
{
var key = HttpUtility.UrlEncode(HttpUtility.UrlDecode(pair.Key));
key = Regex.Replace(key, "(%[0-9a-f][0-9a-f])", c => c.Value.ToUpper()).Replace("%", "%25");
var value = HttpUtility.UrlEncode(HttpUtility.UrlDecode(pair.Value));
value = Regex.Replace(value, "(%[0-9a-f][0-9a-f])", c => c.Value.ToUpper()).Replace("%", "%25");
result.Add(key, value);
}
return result;
}
** But if i try to Get info about products or Delete some product this functions worked fine, **
This code i find on Github https://github.com/kloon/WooCommerce-REST-API-Client-Library
I think, that my function for signature is worked bad, but i don't understand what should be fixed.
Maybe this is an old question. But it will be worth for someone came from google searching any hint.
edit: From the error message, i think you forgot to include the oauth_consumer_key as the message. Make sure your request include the oauth_consumer_key, by check the RestRequest query parameter.
Btw instead using the implementation from kloon, you can use the Woocommerce C# Library from my repository
Try the below solution its very easy to integrate and require very less line of codes.It Works for me
static void Main(string[] args)
{
string requestURL = #"http://www.example.co.uk/test/wp-json/wc/v1/products";
UriBuilder tokenRequestBuilder = new UriBuilder(requestURL);
var query = HttpUtility.ParseQueryString(tokenRequestBuilder.Query);
query["oauth_consumer_key"] = "consumer_key";
query["oauth_nonce"] = Guid.NewGuid().ToString("N");
query["oauth_signature_method"] = "HMAC-SHA1";
query["oauth_timestamp"] = (Math.Truncate((DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds)).ToString();
string signature = string.Format("{0}&{1}&{2}", "POST", Uri.EscapeDataString(requestURL), Uri.EscapeDataString(query.ToString()));
string oauth_Signature = "";
using (HMACSHA1 hmac = new HMACSHA1(Encoding.ASCII.GetBytes("consumer_Secret&")))
{
byte[] hashPayLoad = hmac.ComputeHash(Encoding.ASCII.GetBytes(signature));
oauth_Signature = Convert.ToBase64String(hashPayLoad);
}
query["oauth_signature"] = oauth_Signature;
tokenRequestBuilder.Query = query.ToString();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(tokenRequestBuilder.ToString());
request.ContentType = "application/json; charset=utf-8";
// request.Method = "GET";
request.Method = "POST";
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
string json = File.ReadAllText(#"D:\JsonFile.txt");//File Path for Json String
streamWriter.Write(json);
streamWriter.Flush();
}
var httpResponse = (HttpWebResponse)request.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}

HTTP POST is giving unauthorized 401 Exception

When calling the same method on google chrome postman after logging in, i'm getting the json object as shown below.
but when i try to get the same json result in codebehind (C#). I'm getting Unauthorized 401 exception.
I'm using my code like this.
using (var clientSideTab = new WebClient())
{
var valSideTab = new System.Collections.Specialized.NameValueCollection { { "username", UserID }, { "Password", strPassword } };
string UpldDataSideTab = "https://resapistage.namechanged.com/v3/secure/Login.aspx?userId=" + UserID + "&passwd=" + strPassword + " ";
SystemComponentWrapper SPPostWrapper = new SystemComponentWrapper();
SystemComponentData request = new SystemComponentData();
SystemComponentaddressId addressId = new SystemComponentaddressId();
addressId.type = "AddressId";
addressId.id = 19863;
addressId.serial = "";
request.addressId = addressId;
request.compId = null;
request.getCompParams = true;
request.filterForAddress = false;
SPPostWrapper.request = request;
var postJson = JsonConvert.SerializeObject(SPPostWrapper);
Encoding encoding = new UTF8Encoding();
string postData = postJson.ToString();
byte[] bdata = encoding.GetBytes(postData);
string URI = "https://resapistage.namechanged.com/v3/api/secure/json/AddressInfo.svc/getSystemComponentsV2";
clientSideTab.UploadValues(UpldDataSideTab, "POST", valSideTab);
clientSideTab.Headers.Add("Content-Type","application/json; charset=utf-8");
clientSideTab.Headers.Add("Accept","application/json");
clientSideTab.UploadString(URI,"POST", postData);
//clientSideTab.UploadData(URI, "POST", bdata);
String jsonresponse = "failed";
Label1.Text = jsonresponse;
}
I'm getting this error everytime. please help me.
use like this.
string cookie = strCookie[0]; // fetch your cookie after logging in
clientSideTab.Headers.Add("Content-Type","application/json; charset=utf-8");
clientSideTab.Headers.Add("Accept","application/json");
clientSideTab.m_container.SetCookies(URI, cookie);
//clientSideTab.Headers.Add(HttpRequestHeader.Cookie, cookie);
String resultJSON = clientSideTab.UploadString(URI,"POST", jsonData);
this worked for me. hope this will help you.

Categories

Resources