C# API POST Request - c#

I'm trying to post to an API using C#.
Here is some documentation on the API: http://docs.gurock.com/testrail-api/accessing
Here is what I have so far:
string url = "https://example.testrail.com//index.php?/miniapi/add_result/1&key=19e73cdd99fbad172d3523b13d1c8c8f";
HttpWebRequest req = WebRequest.Create(new Uri(url))as HttpWebRequest;
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
My question is how can I pass in a Status_id of 1 and a comment of "Test" and then post to the API?

You need to call the GetRequestStream method on your req object, and write the post parameters to that

Related

HttpWebRequest returns (400) Bad Request

The request gives the following error:
The remote server returned an error: (400) Bad Request.
I cann't find a solution on internet. Does anyone knows how to solve this?
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(#"https://maps.googleapis.com/maps/api/geocode/json");
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
var parameters = string.Format("language={0}&latlng={1}&client={2}&signature={3}", "nl", "51.123456,5.612345", "gme-aa", "******_******=");
byte[] byteArray = Encoding.UTF8.GetBytes(parameters);
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
/*
* Read HttpWeb Response
*/
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string Response = reader.ReadToEnd();
response.Close();
EDIT:
I'm working inside Lowcode platform Outsystems. Outsystems creates the url inside WebRequest.Create() without the paramaters. So, I have access to webRequest object and need to pass the parameters.
You have to use HTTP "GET" Method.
In a GET request, you pass parameters as part of the query string.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create($"https://maps.googleapis.com/maps/api/geocode/json?language=fr&latlng=51.123456,5.612345&key={apiKey}");
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "GET";
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
string result = new StreamReader(response.GetResponseStream()).ReadToEnd();
}
According the documentation, the API is expecting a POST method and receiving the parameters in the URL and not the body.
If you are using the OutSystems platform you can use the Consume REST API functionality to easily call the web service without using code. Configure your API like this (you can copy the example JSON from the documentation page above):

403 error response when submitting a post request to Instagram

I'm trying to "programmatically" login to Instagram with a HTTP post request. Although, whenever I try to do it to this URL: https://instagram.com/accounts/login/ - it gives me a 404 error. However, if I remove the slash from the end, e.g. /accounts/login, then it will work, however, the response body just seems to be a simple GET request as they simply just output the same as if it was a GET request. I'm actually expecting an error message as response.
The code is written in C# and is nothing fancy; basically a http web request and then I write the post data in the TCP stream. The website is using a CSRF token which needs to be included in the post request, so I first grab this key by using a simple GET request, and then continuing with the POST.
Is there any technical aspect that I'm missing? I've tried the code and done the same on several other websites and all attempts were successful.
The code looks much like this (same problem):
WebResponse Response;
HttpWebRequest Request;
Uri url = new Uri("https://instagram.com/accounts/login/");
CookieContainer cookieContainer = new CookieContainer();
Request = (HttpWebRequest)WebRequest.Create(url);
Request.Method = "GET";
Request.CookieContainer = cookieContainer;
// Get the first response to obtain the cookie where you will find the "csrfmiddlewaretoken" value
Response = Request.GetResponse();
string Parametros = "csrfmiddlewaretoken=" + cookieContainer.GetCookies(url)["csrftoken"].Value + "&username=USER&password=PASSWORD&next="; // This whill set the correct url to access
Request = (HttpWebRequest)WebRequest.Create(url); // it is important to use the same url used for the first request
Request.Method = "POST";
Request.ContentType = "application/x-www-form-urlencoded";
Request.UserAgent = "Other";
// Place the cookie container to obtain the new cookies for further access
Request.CookieContainer = cookieContainer;
Request.Headers.Add("Cookie",Response.Headers.Get("Set-Cookie")); // This is the most important step, you have to place the cookies at the header (without this line you will get the 403 Forbidden exception
byte[] byteArray = Encoding.UTF8.GetBytes(Parametros);
Request.ContentLength = byteArray.Length;
Stream dataStream = Request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
Response = Request.GetResponse(); // Fails here
Thanks in advance!

Foursquare checking using API

I am trying to checkin to Foursquare using the API, I have obtained the oauth_token and am doing a POST request with the oauth_token. According to the documentation the endpoint I'm hitting is https://api.foursquare.com/v2/checkins/add. This however returns a 400 Bad Request message. This is my code in C#
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.foursquare.com/v2/checkins/add?oauth_token"+ oauth_token + "&venueId=" + venueId);
request.Method = "POST";
HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse();
Stream responseStream = webResponse.GetResponseStream();
When I do the same in curl however, it posts a checkin and I get a json response back
curl --data "oauth_token=[oaut_token]&venueId=[venueId]" https://api.foursquare.com/v2/checkins/add
Ultimately what worked is the following:
using (WebClient wc = new WebClient())
{
System.Collections.Specialized.NameValueCollection reqparm = new System.Collections.Specialized.NameValueCollection();
reqparm.Add("oauth_token", oauth_token);
reqparm.Add("venueId", venueId);
byte[] responsebytes = wc.UploadValues(URI, "POST", reqparm);
string responsebody = Encoding.UTF8.GetString(responsebytes);
}
Thanks everyone for your help!
You should write your data to request input stream: HttpWebRequest.GetRequestStream()

retweet with oauth c#

I have tried to use twitter api to retweet a status , and use below code to send a post request
webRequest = WebRequest.Create("https://api.twitter.com/1.1/statuses/retweet/241259202004267009.json") as HttpWebRequest;
webRequest.ServicePoint.Expect100Continue = false;
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Headers.Add("Authorization: OAuth oauth_consumer_key=\"xxxxx\", oauth_nonce=\"xxx\", oauth_signature=\"xxxx\", oauth_signature_method=\"HMAC-SHA1\", oauth_timestamp=\"1352642106\", oauth_token=\"xxxx\", oauth_version=\"1.0\"");
requestWriter = new StreamWriter(webRequest.GetRequestStream());
requestWriter.Write(string.Empty);
requestWriter.Close();
The user is authenticated with my twitter application in previous step but the above code do simply nothing and even do not returning any error.
You need to call webRequest.GetResponse() to actually send the request.

cURL call in C# with flag

I'd like to make a following curl call in C#:
curl "http://localhost:8983/solr/update/extract?literal.id=doc1&commit=true" -F "myfile=#tutorial.html"
I found that I should use WebRequest class, but I'm still not sure how deal with this part:
-F "myfile=#tutorial.html"
The code snippet from http://msdn.microsoft.com/en-us/library/debx8sh9.aspx shows how to send POST data using the WebRequest class:
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create("http://localhost:8983/solr/update/extract?literal.id=doc1&commit=true");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = "myfile=#tutorial.html";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
As an alternative to WebRequest, you might consider using the WebClient class. It offers what might be considered to be a cleaner and simpler syntax than WebRequest. Something like this:
using (WebClient client = new WebClient())
{
client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
byte[] postResult = client.UploadFile("http://localhost:8983/solr/update/extract?literal.id=doc1&commit=true", "POST", "tutorial.html");
}
See http://msdn.microsoft.com/en-us/library/esst63h0%28v=vs.100%29.aspx

Categories

Resources