How to pass body data with UploadStringAsync C# - c#

I'm trying pass a string in the body of my POST request using WebClient class. Below is my code:
protected void GetAccessToken(string client_id, string secret)
{
var urlEncodedSecret = HttpUtility.UrlEncode(secret);
var urlEncodedSid = HttpUtility.UrlEncode(client_id);
string bodyData = String.Format("grant_type=client_credentials&client_id=ms-app%3a%2f%2f{0}&client_secret={1}&scope=notify.windows.com", client_id, secret);
string address = "https://login.live.com/accesstoken.srf";
string myParameters = "param1=value1&param2=value2&param3=value3";
Uri URI = new Uri(address);
System.Net.WebClient webClient = new WebClient();
webClient.BaseAddress = address;
webClient.Headers["Content-Type"] = "application/x-www-form-urlencoded";
webClient.Headers["Content-Length"] = "211";
webClient.Headers["Host"] = "https://login.live.com";
webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(uploadStringCompleted);
webClient.UploadStringAsync(URI, "POST", bodyData);
}
private void uploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
string json = e.Result.ToString();
_oAuthToken = GetOAuthTokenFromJson(json);
}
When i run the application, i received the exception "The remote server returned an error: NotFound.".
I succeeded to make the same request using the Postman:
Anyone know something wrong about my request? Or something that puting me on a right way!?

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/

Getting parameter_rejected error in quickbook online integration

I have done this code:
static void Main (string[] args)
{
Console.WriteLine("Authenticating..");
string consumerkey = "L0ORES0pf0uEody1YDI3sTkTpyBGaDVVnVRBb1krprkrghPWLQ";
string consumerSecret = "NAONcYrwGgpkFCJN2BgXZHjG8YLqn1JWMEPDXIMg";
string REQUEST_TOKEN_URL = "https://oauth.intuit.com/oauth/v1/get_request_token";
string ACCESS_TOKEN_URL = "https://oauth.intuit.com/oauth/v1/get_access_token";
string OauthLink = "https://developer.intuit.com/v2/OAuth2Playground/RedirectUrl";
var consumerContext = new OAuthConsumerContext
{
ConsumerKey = consumerkey,
ConsumerSecret = consumerSecret,
SignatureMethod = SignatureMethod.HmacSha1
};
IOAuthSession AuthSession = new OAuthSession(consumerContext,REQUEST_TOKEN_URL, OauthLink, ACCESS_TOKEN_URL);
IToken requestToken = AuthSession.GetRequestToken();
}
And I am getting error : An unhandled exception of type 'DevDefined.OAuth.Framework.OAuthException' occurred in DevDefined.OAuth.dll Additional information: parameter_rejected
I have attached screenshot of my error.
What is quickbook online Request token URL and Access token URL for OAuth 2.0?
Oauth2.0 //Refresh and Get New Access Token through WebClient and build ServiceContext for CRUD operations
Access Token will expire in every 60 minutes
string URI = "https://oauth.platform.intuit.com/oauth2/v1/tokens/bearer";
string myParameters = "grant_type=refresh_token&refresh_token=L0115-----------------------------------"; // Put Refresh Token
WebClient wc = new WebClient();
wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
wc.Headers[HttpRequestHeader.Accept] = "application/json";
wc.Headers[HttpRequestHeader.Authorization] = "Basic UT------------------------------hcW5SV---------------------Qg=="; // Add Auth Token
string HtmlResult = wc.UploadString(URI, myParameters);
wc.Dispose();
var jobject = JsonConvert.DeserializeObject<Test>(HtmlResult);
string accessToken = jobject.access_token;
string relmid = "123412341234123421341234"; // Relmid
OAuth2RequestValidator oauthValidator = new OAuth2RequestValidator(accessToken);
ServiceContext serviceContext = new ServiceContext(relmid, IntuitServicesType.QBO, oauthValidator);
serviceContext.IppConfiguration.BaseUrl.Qbo = "https://sandbox-quickbooks.api.intuit.com/";
//serviceContext.IppConfiguration.BaseUrl.Qbo = "https://quickbooks.api.intuit.com/";//prod
serviceContext.IppConfiguration.MinorVersion.Qbo = "23";
CustomerCRUD.CustomerAddTestUsingoAuth(serviceContext);
CustomerCRUD.CustomerFindAllTestUsingoAuth(serviceContext);

Yahoo Weather API using Oauth

I am stuck on implementing the Yahoo Weather private API call. This is my code snippet, whenever I call it using valid clientId & Secret it returns 401 (unauthorized).
var outhWc = new WebClient();
outhWc.Credentials = new NetworkCredential(clientId, clientSecret);
outhWc.Headers.Add(HttpRequestHeader.Accept, "application/json");
var outhresponse = outhWc.DownloadData("https://query.yahooapis.com/v1/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22nome%2C%20ak%22)&format=json");
It always throws an exception. I also try to pass username and password in NetworkCredentials and also try to pass clientId and Secret in Header but I cannot find a successful call.
So I've been stuck with the same issue here. Finally I implemented the following code, based on the oAuth c# simple class found at http://oauth.googlecode.com/svn/code/csharp/OAuthBase.cs
public void LoadWeather() {
string URLDes, Params = "";
string Signature, BaseURL, cKey, cSecret = "";
OAuthBase oAuth = new OAuthBase();
BaseURL = "http://weather.yahooapis.com/forecastrss?w=" + textBox1.Text + "&u=f";
cKey = "YOUR API KEY";
cSecret = "YOUR API SECRET";
Signature = oAuth.GenerateSignature(new Uri(BaseURL), cKey, cSecret, "", "", "GET", oAuth.GenerateTimeStamp(), oAuth.GenerateNonce(), out URLDes, out Params);
WebClient wc = new WebClient();
wc.DownloadStringCompleted += HttpsCompleted;
wc.DownloadStringAsync(new Uri(String.Format("{0}?{1}&oauth_signature={2}", URLDes, Params, Signature)));
}
private void HttpsCompleted(object sender, DownloadStringCompletedEventArgs e) {
if (e.Error == null) {
XDocument xdoc = XDocument.Parse(e.Result, LoadOptions.None);
xdoc.Save("c:\\weather.xml");
richTextBox1.Text = xdoc.FirstNode.ToString();
} else {
richTextBox1.Text = e.Error.Message;
}
}
As you can see, I already have the city ID. This sample downloads the xml string returned by the API. Worked for me, hope it helps!

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.

c# - How to reply for comment in LinkedIn?

I'm trying to integrate LinkedIn in our application. I just want to know how to reply for comment in LinkedIn.
I've written this code.
protected void Page_Load(object sender, EventArgs e)
{
string data = "<comments><comment><text>Check out the Reply!</text></comment></comments>";
byte[] databytes = Encoding.UTF8.GetBytes(data);
var request = new RestRequest { Path = "comments" };
var credentials = new Hammock.Authentication.OAuth.OAuthCredentials
{
Type = OAuthType.AccessToken,
SignatureMethod = OAuthSignatureMethod.HmacSha1,
ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
ConsumerKey = "kmkzt9cqml1s",
ConsumerSecret = "hNiwIrZWGSMykoD2",
Token = "b3cbdca7-37a7-474f-a9a6-e21bb89917fe",
TokenSecret = "990f1b78-79de-4490-b4e3-893b4e020e45",
};
var client = new RestClient()
{
Authority = "http://api.linkedin.com/v1/posts/g-457832-S-454334",
Credentials = credentials,
Method = WebMethod.Post,
};
client.AddHeader("Content-Type", "text/xml");
client.AddPostContent(databytes);
RestResponse response = client.Request(request);
string content = response.Content;
}
I'm getting an error in content in the below format
<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>
<error>
<status>400</status>
<timestamp>1374494502579</timestamp>
<request-id>QM4MYPEKJJ</request-id>
<error-code>0</error-code>
<message>Couldn't parse message document: error: Unexpected end of file after null</message>\n</error>\n"
Any ideas? Thanks in advance.

Categories

Resources