api - C# webapi POST via console program -
i have web api can access through browser :-
i trying create simple console program in c# using vs2015 send data , receive response using http post.
here have far:-
using system; using system.net.http; using system.net.http.headers; using system.threading.tasks; namespace websample { class apisenddata { public string userid { get; set;} // username public string password { get; set;} // password webapi public string apifunction { get; set; } public string dppname { get; set; } public string cleardata { get; set; } public string dppversion { get; set; } } class program { static void main(string[] args) { // main function calls async method named runasync // , blocks until runasyncc completes. runasync().wait(); } static async task runasync() { using (var client = new httpclient()) { //specify use tls 1.2 default connection system.net.servicepointmanager.securityprotocol = securityprotocoltype.tls12 | securityprotocoltype.tls11 | securityprotocoltype.tls; // code sets base uri http requests, // , sets accept header "application/json", // tells server send data in json format. client.baseaddress = new uri("https://localhost:8443/"); client.defaultrequestheaders.accept.clear(); client.defaultrequestheaders.accept.add(new mediatypewithqualityheadervalue("application/json")); // http post var datatobesent = new apisenddata() { userid = "xxxx", password = "yyyy", apifunction ="ncrsecuredata", dppname ="csamplecustomer", dppversion ="latest", cleardata ="1234567890", resulttype = "json" }; httpresponsemessage response = await client.postasjsonasync("ncrapi", datatobesent); if (response.issuccessstatuscode) { // uri of created resource. uri ncrurl = response.headers.location; // whatever need here returned data // } } } } }
in response variable 200 ok http 1.1 message, content type = application/json , content-length = 174... no actual data received...
the variable ncrurl null....
i wondering if need additional statements in console program receive data?
here have been following:- http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client
upon reading comments seems api configured return file instead of string content such json or xml. can use httpcontent.readasstreamasync method read response stream , save file.
httpresponsemessage response = await client.postasjsonasync("ncrapi", datatobesent); using (stream output = file.openwrite("filename.txt")) // change { using (stream input = await response.content.readasstreamasync()) { input.copyto(output); } }
Comments
Post a Comment