Translating this to a HTTP POST in C# - c#

I am currently experimenting with the HTTP request. I have successfully managed to do get requests and I have read on doing post request with HTTP request.
Now I am trying to work with the yahoo API and in order to use the Yahoo api it states that at
The Message Management API can be used to send a message to another
Yahoo! Messenger contact. The API is very simple to use, as shown
here. Note that the contact that the message is sent to is part of the
URI, using the following format:<server>/v1/message/<network>/<contactID>
POST /v1/message/yahoo/targetYahooId?sid=msgrsessionid
Host: rcore1.messenger.yahooapis.com
Authorization: < Standard OAuth credentials >
Content-Type: application/json;charset=utf-8
Content-Length: 25
{
"message" : "Hey there"
}
Now I have an OAuth string which I obtained from get using the HttpWebRequest object.
The string is something like this
oauth_token=A%3Dvh....aRg--&oauth_token_secret=bd46a....c9239&oauth_expires_in=3600&oauth_session_handle=ALtT.....3J1N4Zg--&oauth_authorization_expires_in=784964948&xoauth_yahoo_guid=TUSKED5...NCIA
UPDATE
Now my question are as follows :
1- If I am using WebRequest object in C# what would my URI look like
2- I understand that it requires a JSON type object. How do i even know what OAuth parameters are ?

One thing you'll need to change is the content type:
request.ContentType = "application/json;charset=utf-8";
And of course, the url.

you need to change the url on the line with the url in it
you need to change the content-type line
you need to make the payload into a json string then convert it to a byte array (byteArray in the sample)
either assemble the json by hand "{ foo:'bar'}" etc or use json.net
and set the content-length

Looks like it's expecting a JSON object for the request body. Depending on the version of .NET you're using, you can either use a Javascript serializer as shown here (https://stackoverflow.com/a/7003815/939080) or JSON.NET (http://james.newtonking.com/projects/json-net.aspx) to convert your form collection into JSON output.

You are asking an open-ended question that would require people to write a bunch of code for you if you want a specific and complete answer. As others have pointed out, there are several issues that you'd need to deal with:
The JSON payload, which would be a straightforward matter of putting the JSON string in the request body via the byteArray used in the code sample.
The content type, which you would need to change as described by jrummell.
The OAuth credentials, which is a kettle of fish you'll need to read about, understand, and acquire a library for. Here's a good place to start looking for a library.

Related

Put call works in PostMan but not in RestSharp: Getting a bad request

I want to call an endpoint with a Put command.
In Postman
I can put example https://example.com/customers/106. I then add a body of type application/json (under raw).
When I Put this body to the endpoint, I get a 200 OK.
The endpoint I use requires two custom headers and a content-type, which I have made under headers. So I add three headers: X-AppSecretToken, X-AgreementGrantToken and the Content-Type (to application/json).
In RestSharp
Here I use the following. The putstr is the exact same body I Put as I do in Postman:
var restclient = new RestSharp.RestClient("https://example.com");
var request = new RestRequest("/customers/" + customerId, Method.PUT);
request.AddHeader("X-AppSecretToken", systemToken);
request.AddHeader("X-AgreementGrantToken", userToken);
request.AddHeader("Accept", "application/json");
request.AddJsonBody(putstr);
var response = restclient.Execute(request);
Now, when I do this, I get the following response which is a custom error from the API I am calling:
"{\"message\":\"Error converting value SOME STUFF}}\\\" to type 'eco.rest.Models.Customer'. Path '', line 1, position 605.\",\"errorCode\":\"E00500\",\"developerHint\":\"The JSON payload could not be parsed. The error message should give you a good indication of where the error is located. One common reason for this error is a missing '{' or a '}' in your payload.\",\"logId\":\"123fc6fb4964a141f612ae8ae7571446\",\"httpStatusCode\":400,\"logTime\":\"2018-05-20T21:56:56\"}"
How to fix?
Normally, I'd never ask this question. If someone else asked, I would say: open Fiddler or a similar tool and see how requests are different.
I have some troubles with this, because it's HTTPS.
When I debug through my code, I simply don't see the call inside Fiddler. I also installed Charles, but also no luck. Not sure what the problem is.
However, I thought that someone who reads this can probably come up with the problem. My own assumptions are I maybe have added the headers in a wrong way, the JSON body is encoded different or similar - but I am really unsure how to move on. I hope someone can help!
Your putstr value seems to be a JSON value.
AddJsonBody will convert this JSON value into another JSON value.
You should use the original object instead of putstr.

How to access the HTTP request body using RestSharp?

I'm building a RESTful API client using C# .NET 3.5.
I first started building it with the good old HttpWebClient (and HttpWebResponse), I could do whatever I wanted with. I were happy. The only thing I stumbled upon was the automatic deserialization from JSON response.
So, I've heard about a wonderful library called RestSharp (104.1) which eases the development of RESTful API clients, and automatically deserialize JSON and XML responses. I switched all my code on it, but now I realize I can't do things I could do with HttpWebClient and HttpWebResponse, like access and edit the raw request body.
Anyone has a solution?
Edit: I know how to set the request body (with request.AddBody()), my problem is that I want to get this request body string, edit it, and re-set it in the request (in other words: updating the request body on the fly)
The request body is a type of parameter. To add one, you can do one of these...
req.AddBody(body);
req.AddBody(body, xmlNamespace);
req.AddParameter("text/xml", body, ParameterType.RequestBody);
req.AddParameter("application/json", body, ParameterType.RequestBody);
To retrieve the body parameter you can look for items in the req.Parameters collection where the Type is equal to ParameterType.RequestBody.
See code for the RestRequest class here.
Here is what the RestSharp docs on ParameterType.RequestBody has to say:
If this parameter is set, it’s value will be sent as the body of the
request. The name of the Parameter is ignored, and so are additional
RequestBody Parameters – only 1 is accepted.
RequestBody only works on POST or PUT Requests, as only they actually
send a body.
If you have GetOrPost parameters as well, they will overwrite the
RequestBody – RestSharp will not combine them but it will instead
throw the RequestBody parameter away.
For reading/updating the body parameter on-the-fly, you can try:
var body = req.Parameters.FirstOrDefault(p => p.Type == ParameterType.RequestBody);
if (body != null)
{
Console.WriteLine("CurrentBody={0}", body.Value);
body.Value = "NewBodyValue";
}
Or failing that, create a new copy of the RestRequest object with a different body.

How to send json using GET method to REST like API

I must implement method in my application which will send some data (which according to api documentation should be JSON) using GET method (it is weird...). How I can do this using c sharp in windows 8 (RestSharp lib is not working there). I don't have any experience in REST clients but I have already implement other features but there data was sended by POST or DELETE methods. I have tried "tranlate" json to get like this:
JSON:
{
a = "foo",
b = "bar
}
GET URL:
__SITE__?a=foo&b=bar
But server return null values (not error). I don't know how to deal with this thing :/
Thanks for help in advance :)
If you have api you have name of param that you should send. Just convert the data into json and sind is as this param.
If you have to send json why you`re sending param a and b as 2 diffrent strings ?
remember that a GET method can be invoked by HttpClient. Just invoke the URL
Finally it turned out (in my case) that API also accepts providing data in that way: URL?a=foo&b=bar regardless of the fact that it should be json.
Long story short, I think this will be most illuminating .. it "fills in the blanks" with using HttpClient to fire JSON Formatted data at a REST API
How do you set the Content-Type header for an HttpClient request?

Calling C# from JavaScript with parameters

I'm using source files found at http://www.thecssninja.com/javascript/gmail-upload (all credit goes to CSSNinja for the code). And what I'm having an issue with is I basically need to convert a section of this JavaScript to interface with C#, the problem is i really don't know JavaScript. I need to be able to save the files to specific directories with specific file names based on Session variables. Current the script calls a simple php, and I don't know how to use PHP to interface with Sessions. Any help would be awesome.
xhr.open("POST", "upload.php");
xhr.setRequestHeader("If-Modified-Since", "Mon, 26 Jul 1997 05:00:00 GMT");
xhr.setRequestHeader("Cache-Control", "no-cache");
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.setRequestHeader("X-File-Name", file.fileName);
xhr.setRequestHeader("X-File-Size", file.fileSize);
xhr.setRequestHeader("Content-Type", "multipart/form-data");
xhr.send(file);
The question is basically how to convert the above to interface with a class in C#, passing in any/one parameter that is above.
PHP code
<?php
$headers = getallheaders();
// create the object and assign property
$file = new stdClass;
$file->name = basename($headers['X-File-Name']);
$file->size = $headers['X-File-Size'];
$file->content = file_get_contents("php://input");
// if everything is ok, save the file somewhere
echo $file->content;
?>
All right, enough comments...
All that JavaScript is doing is sending you two special HTTP headers and a file stream as the request body, and the PHP is reading that. Nothing more.
setRequestHeader(name, value) sets a normal HTTP header with the name name and the value value, while the file content is sent as a normal request body. All standard HTTP.
If you know your C# (and presumably ASP.NET), accessing two HTTP headers and reading the request stream should be no problem.

What is a structure of a standard POST request

I am using C# for my project, can anyone tell me what is a standered structure of a HTTP POST Requset. How to attach POST data like a file in the Request from code.
Simply i want to create a POST request from my code itself, with diffrent items to be posted available.
I have checked Ietf's RFC for http POST but its too long....
Specs for simple reference
I have always appreciated HTTP Made Really Easy as a starting point. It's small, concise and friendly.
Often you can get enough implementation details (or at least enough understanding) from this guide's simple style to suffice your need. It has worked for me many times. There is a section on POST. The guide builds cumulatively.
Additionally it links to proper specifications and fuller resources should you need to reference them and get into more detail.
.NET Supporting Classes
Fortunately the .NET Framework Class Library contains higher level classes that can simplify your life. Look into the MSDN documentation and examples about System.Net.WebClient (doesn't lend itself as well to POST, favours GET for quick usage methods). Consider the more flexible System.Web.HttpRequest and System.Web.HttpResponse counterpart classes.
Example using C#
This code sample shows the concept of posting binary data to a stream.
This method is called like:
PostMyData(Stream_instance, "http://url_to_post_to");
Namespaces involved are:
using System.IO;
using System.Net;
The custom method would look something like the following.
Note: Concept taken from MSDN sample code here.
Although I use MIME type application/octet-stream for generic binary data, you can use any well known type from this list of mime types to target the kind of binary data you are sending.
public int PostMyData(Stream binaryData, string postToUrl) {
// make http request
var request = (HttpWebRequest)WebRequest.Create(postToUrl);
request.Method = "POST";
request.ContentType = "application/octet-stream"; // binary data:
// data (bytes) that will be posted in body of request
var streamOut = request.GetRequestStream();
binaryData.CopyTo(streamOut);
// post and get response
using (var response = (HttpWebResponse)request.GetResponse()) {
var code = response.StatusCode;
return (int)code;
}
}
Use HttpWebRequest, its always the best way, but for a more simple aproach on Http Post read:
http://programaticallyspeaking.site40.net/blog/2010/11/how-to-implement-an-http-server-part-1/
Hey i found a way to view a sample POST request, Use Fiddler to track HTTp transfers and click on RAW to view raw data being transfered.

Categories

Resources