.net - calling the rest api post from mvc -
i want post restful service name of url "https://api.pipedrive.com/v1/persons?api_token=ts5adsxc6v2nh991"
list of complete api present in "https://developers.pipedrive.com/v1"
following code
string url = "https://api.pipedrive.com/v1/persons?api_token=ts5adsxc6v2nh991"; string data = @"{""object"":{""name"":""rohit sukhla""}}"; var datatosend = encoding.utf8.getbytes(data); //passyour service url create method var req = httpwebrequest.create(url); req.contenttype = "application/json"; req.contentlength = datatosend.length; req.method = "post"; req.getrequeststream().write(datatosend, 0, datatosend.length); var response1 = req.getresponse();
i getting error
the remote server returned error: (400) bad request.
please help
here's usual strategy posting external apis, hope helps
using (var http = new httpclient()) { // define authorization headers here, if // http.defaultrequestheaders.add("authorization", authorizationheadervalue); var data = new modeltype { name = namevalue, email = emailvalue }; var content = new stringcontent(jsonconvert.serializeobject(data)); content.headers.contenttype = new mediatypeheadervalue("application/json"); var request = http.postasync("[api url here]", content); var response = request.result.content.readasstringasync().result; return jsonconvert.deserializeobject<responsemodeltype>(response); }
the request
can awaited, instead of calling .result
directly.
to use approach need create c# model based on response json structure. oftentimes use http://json2csharp.com/, provide typical json response endpoint i'm interested in, , c# model gets generated me automatically.
Comments
Post a Comment