locked
Post data in restful json web service RRS feed

  • Question

  • User-139960961 posted

    Hi,

    How do i post data in json asI keep receive that I have not passed the parameter.. This is my c# code:

    Firing the button:  
    url = szAPIURL + url;
                    
               
    
                WebClient postWithParamsClient = new WebClient();
                postWithParamsClient.UploadStringCompleted += new UploadStringCompletedEventHandler(postWithParamsClient_UploadStringCompleted);
    
                postWithParamsClient.Headers["Content-Length"] = postdata.Length.ToString();
                postWithParamsClient.UploadStringAsync(new Uri(url), "POST", "?username=name123&password=pass123");
    
    
    
         private void postWithParamsClient_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
            {
                if (e.Error == null)
                MessageBox.Show("WebClient: " + e.Result);
                else
                MessageBox.Show("WebClient: " + e.Error.Message);
            }


    This is what I call receive:

    [{"error_code":2,"error_messages":["You must specify login user name and password"],"tokenid":"","userid":0}]



    Friday, March 22, 2013 11:28 AM

Answers

  • User-742633084 posted

    Hi weihan1394,

    For sending HTTP requests, I'd recommend using HttpWebRequest class which provides more advanced options and is more flexible than WebClient class.

    #How to: Send Data Using the WebRequest Class
    http://msdn.microsoft.com/en-us/library/debx8sh9.aspx

    for sending JSON data, you just need to compose the json format data text and write it into the request stream of the WebRequest object. Here are some references:

    #Making a JSON service request using C#
    http://blog.manglar.com/json-post-request/

    #json call with C#
    http://stackoverflow.com/questions/4982765/json-call-with-c-sharp

    The most important thing is that you need to first verify what kind of request data the server/service is expecting. Generally, a simple way to do this is get a working client to send some requests to server. And you can use fiddler or other web debugger tools to capture the HTTP requests sent by the working client and inspect the request data (JSON text) it sends. Thus, you can try composing the same data in your .NET WebRequest code.

    #fiddler web debugging proxy
    http://www.fiddler2.com/fiddler2/

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, March 26, 2013 6:24 AM