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
Related
I am struggling with the syntax to make a POST web request with parameters. I get a response back but not data and it should I'm suspecting it is because I am not passing the parameters right.
What is also strange if I use a string "[100,200]" and send that over and let C# compiler convert the string over to int[] it's almost like the data isn't getting sent.
The api method looks like:
public string GetPersonInfo(int64[] personsIds)
Then here is my api request (parameter part)
HttpWebRequest = (HttpWebRequest)HttpWebRequest.Create("MyApicall.com/api/Persons/GetPersonInfo");
int[] numArray = new int[]{100,200};
byte[] sendInfo = new byte[numArray.length * sizeof(int)];
Buffer.BlockCopy(numArray,0,sendInfo,sendInfo.length);
request.Headers["Accept-Languages"] = "en-Us";
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = sendInfo.length;
Stream curStream = request.GetRequestStream();
curStream.Write(sendInfo,0,sendInfo.length);
curStream.Close();
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
I'm trying to retrieve the oauth access token to make calls to some google apis in asp.net mvc, and I wrote the following code for an action:
public ActionResult GetOAuthToken()
{
String url = "https://accounts.google.com/o/oauth2/token";
// Create a request using a URL that can receive a post.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
// Set the Method property of the request to POST.
request.Method = "POST";
request.Host = "accounts.google.com";
// Create POST data and convert it to a byte array.
string postData = String.Format("code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type=authorization_code", Request.QueryString["code"].ToString(), OAuthConfig.client_id, OAuthConfig.client_secret, OAuthConfig.token_redirect_uri);
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] byteArray = encoding.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;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = request.GetResponse();
// SOME CODE TO PROCESS THE RESPONSE
Response.Redirect("/Home");
return View();
}
OAuthConfig is just a class that contains the client id, client secret etc.
I keep getting 'The remote server returned an error: (400) Bad Request.' at the request.GetResponse() line. Where am I going wrong?
Google does provide a higher level library to work with its services, this handles the formatting of the urls and I find it makes it a lot easier to work with their apis. See http://code.google.com/p/google-api-dotnet-client/
i am facing a problem where i try to communicate with a Ruby API from a C# application.
I need to POST some JSON data, with the parameter name "data" but the API return me: '!! Unexpected error while processing request: invalid %-encoding'.
I tried with Content-Type set to 'application/json' and 'application/x-www-form-urlencoded; charset=utf-8'.
My POST data look like this 'data=some_json_string'.
I figure i should escape the json string, so if it is my problem, how to do it with .NET without using a 3rd party library?
Code:
byte[] data = System.Text.ASCIIEncoding.UTF8.GetBytes(sdata);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(url, UriKind.Absolute));
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded; charset=utf-8";
request.ContentLength = data.Length;
Stream reqStream = request.GetRequestStream();
// Send the data.
reqStream.Write(data, 0, data.Length);
reqStream.Close();
Thanks in advance!
Presuming the string sdata coming in is already in JSON format you could do:
using (WebClient wc = new WebClient())
{
string uri = "http://www.somewhere.com/somemethod";
string parameters = "data=" + Uri.EscapeDataString(sdata);
wc.Headers["Content-type"] = "application/x-www-form-urlencoded";
string result = wc.UploadString(uri, parameters);
}
Depending on the consuming service it may need the Content-type set to application/json?
I need to upload an ics file to a REST API. The only example given is a curl command.
The command used to upload the file using curl looks like this:
curl --user {username}:{password} --upload-file /tmp/myappointments.ics http://localhost:7070/home/john.doe/calendar?fmt=ics
How can I do this using a HttpWebRequest in C# ?
Also note that I may only have the ics as a string (not the actual file).
I managed to get a working solution. The quirk was to set the method on the request to PUT instead of POST. Here is an example of the code I used:
var strICS = "text file content";
byte[] data = Encoding.UTF8.GetBytes (strICS);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create ("http://someurl.com");
request.PreAuthenticate = true;
request.Credentials = new NetworkCredential ("username", "password");;
request.Method = "PUT";
request.ContentType = "text/calendar";
request.ContentLength = data.Length;
using (Stream stream = request.GetRequestStream ()) {
stream.Write (data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse ();
response.Close ();