Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Learning how to post to JSON webservice in C#

Options
  • 22-01-2013 4:58pm
    #1
    Registered Users Posts: 7,501 ✭✭✭


    I want to learn how to do this but i dont have a JSON webservice.

    Anyone know of a simple test service i could use to just accept POST messages and respond with anything indicating the message was received?


Comments

  • Registered Users Posts: 220 ✭✭breadmonster




  • Registered Users Posts: 7,501 ✭✭✭BrokenArrows



    Cool. That should do the trick nicely.


  • Registered Users Posts: 1,266 ✭✭✭Overflow


    I want to learn how to do this but i dont have a JSON webservice.

    Anyone know of a simple test service i could use to just accept POST messages and respond with anything indicating the message was received?

    It would take you a few minutes to create a mock one with a ASP.NET MVC website.

    Just create a new MVC website from the templates in VS. Open the home controller and create a few Actions. From each action just return a JSON Result serialized with a List of anonymous objects, here is some example code for the Action:
    public JsonResult Products()
    {
        var items = new List<object> {
           new { id = 1, name = "Blah blah 1", age = 16 },
           new { id = 2, name = "Blah blah 2", age = 14 },
           new { id = 3, name = "Blah blah 3", age = 17 }
        };
     
        return Json(new { success = true, data = items });
    }
    


  • Registered Users Posts: 7,501 ✭✭✭BrokenArrows


    Ive been having a play about with this today and monitoring whats being sent/received using wireshark.

    One thing ive noticed is that it doesnt do everything in one go.

    It seems to go:

    1) HTTP Post
    2) My Proxy responds with "407 Authorization Required"
    3) HTTP Post
    4) Web Service responds with "401 Unauthorized"
    5) HTTP Post
    6) 400 Bad Request <- Im not so much concerned with this, im probably just not sending something correctly.

    Below roughly the code im using. Any reason why it needs 3 separate HTTP Posts or is this normal for HTTP protocol?
    try
    {
    	var httpWebRequest = (HttpWebRequest)WebRequest.Create("URL HERE");
    	httpWebRequest.ContentType = "application/json; charset=utf-8";
    	httpWebRequest.Method = "POST";
    	httpWebRequest.Accept = "application/json; version=1.0";
    	httpWebRequest.Proxy.Credentials = CredentialCache.DefaultCredentials;
    	httpWebRequest.Credentials = new NetworkCredential("username", "password");
    
    	using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
    	{
    	    string json = string.Empty;
    
    	    StringBuilder js = new StringBuilder();
    
    	    js.append("stuff here");
    
    	    json = js.ToString();
    
    	    streamWriter.Write(json);
    	    streamWriter.Flush();
    	    streamWriter.Close();
    	}
    
    	var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
    	
    	using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
    	{
    	    var result = streamReader.ReadToEnd();
    	    Console.WriteLine((string)result);
    	}
    
    	}
    	catch (Exception e)
    	{
    	    Console.WriteLine(e.ToString());
    	}
    }
    
    


  • Registered Users Posts: 2,022 ✭✭✭Colonel Panic


    So you're behind a work proxy? How about getting that bit sorted first? Try a GET request to Google using a HttpWebRequest first.

    Furthermore, are you POSTing to an endpoint of the Twitter API linked above? Have you got the required OAuth authentication key?


  • Advertisement
  • Registered Users Posts: 7,501 ✭✭✭BrokenArrows


    Yes im doing this at work. I get some time to improve my skill set during work.

    Im not concerned about it actually working at the moment.

    Im just curious as to why it does 3 HTTP Posts?

    Why doesnt the webrequest just include the Proxy-Authorization and webservice Authorization in the first message rather than first attempting without any credentials?


  • Registered Users Posts: 2,022 ✭✭✭Colonel Panic


    I dunno, what are you using to look at the outgoing requests? What is the content of the responses? If not authorised, does your proxy look for a login?

    We're not in your environment and it's up to you to actually look at the responses in code! You're setting the proxy credentials to be the default credentials, is that correct? Did you look up the Proxy property of HttpWebRequest?

    Then you set the HttpWebRequest's credentials to some username and password. What username and password? Not your proxy's surely?

    See what I mean, you're just throwing code at the wall and wondering why things are happening instead of actually starting small, with a GET that works through your proxy, and building it up!


  • Registered Users Posts: 7,501 ✭✭✭BrokenArrows


    I dunno, what are you using to look at the outgoing requests? What is the content of the responses? If not authorised, does your proxy look for a login?

    We're not in your environment and it's up to you to actually look at the responses in code! You're setting the proxy credentials to be the default credentials, is that correct? Did you look up the Proxy property of HttpWebRequest?

    Then you set the HttpWebRequest's credentials to some username and password. What username and password? Not your proxy's surely?

    See what I mean, you're just throwing code at the wall and wondering why things are happening instead of actually starting small, with a GET that works through your proxy, and building it up!

    I think you have misunderstood what im getting at. Or i just have not explained myself correctly. Probably the latter!

    My code works fine. It sends the POST and it gets through my firewall and authenticates with the webservice.

    What im getting at is when i send my message i am monitoring the post using Wireshark (Which i mentioned above already).

    Using wireshark i see the following happening when the above code is executed:

    1) HTTP Post (Contains no proxy or web service auth information)
    2) My Proxy responds with "407 Authorization Required"
    3) HTTP Post (Contains proxy auth information and successfully gets through firewall)
    4) Web Service responds with "401 Unauthorized"
    5) HTTP Post (Contains webservice auth information and successfully connects to the webservice)
    6) Response from webservice (Currently response with a failure but that doesnt matter)

    My question is why does the HTTP post attempt without all information the first time.
    It only attempts a HTTP Post with the required information after it fails the first time?

    This doesnt seem to be anything to do with my code as i dont have a loop. I just do one attempt but the above it what happens automatically.

    I have attached a screenshot of wireshark.


  • Registered Users Posts: 2,022 ✭✭✭Colonel Panic


    As I said, I don't know, it's probably something to do with your environment. Although if the code works fine, what's with the 407s and 401s? I'm sure you'll work it out.


  • Registered Users Posts: 2,021 ✭✭✭ChRoMe


    Is the web service secured using NTLM?

    When you hit the URL in the browser, does it ask you to specify a domain (along with the username and password)?


  • Advertisement
  • Registered Users Posts: 1,266 ✭✭✭Overflow


    You haven't done anything wrong, this is normal http protocol.


  • Registered Users Posts: 7,501 ✭✭✭BrokenArrows


    Overflow wrote: »
    You haven't done anything wrong, this is normal http protocol.

    Thanks.


Advertisement