Upload JSON via WebClient

前端 未结 2 1826
后悔当初
后悔当初 2021-01-17 23:48

I have a web app with that is using JQuery to interact with my backend. The backend successfully accepts JSON data. For instance, I can successfully send the following JSON:

2条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-18 00:10

    Although the question is already answered, I thought it would be nice to share my simple JsonService, based on the WebClient:

    Base class

    /// 
    /// Class BaseJsonService.
    /// 
    public abstract class BaseJsonService
    {
        /// 
        /// The client
        /// 
        protected WebClient client;
    
        /// 
        /// Gets the specified URL.
        /// 
        /// The type of the attribute response.
        /// The URL.
        /// The configuration complete.
        /// The configuration error.
        public abstract void Get(string url, Action onComplete, Action onError);
        /// 
        /// Sends the specified URL.
        /// 
        /// The type of the attribute response.
        /// The URL.
        /// The json data.
        /// The configuration complete.
        /// The configuration error.
        public abstract void Post(string url, string jsonData, Action onComplete, Action onError);
    }
    

    Service implementation

    /// 
        /// Class JsonService.
        /// 
        public class JsonService : BaseJsonService
        {
            /// 
            /// Gets the specified URL.
            /// 
            /// The type of the attribute response.
            /// The URL.
            /// The configuration complete.
            /// The configuration error.
            public override void Get(string url, Action onComplete, Action onError)
            {
                if (client == null)
                    client = new WebClient();
    
                client.DownloadStringCompleted += (s, e) =>
                {
                    TResponse returnValue = default(TResponse);
    
                    try
                    {
                        returnValue = JsonConvert.DeserializeObject(e.Result);
                        onComplete(returnValue);
                    }
                    catch (Exception ex)
                    {
                        onError(new JsonParseException(ex));
                    }
                };
    
                client.Headers.Add(HttpRequestHeader.Accept, "application/json");
                client.Encoding = System.Text.Encoding.UTF8;
    
                client.DownloadStringAsync(new Uri(url));
            }
            /// 
            /// Posts the specified URL.
            /// 
            /// The type of the attribute response.
            /// The URL.
            /// The json data.
            /// The configuration complete.
            /// The configuration error.
            public override void Post(string url, string jsonData, Action onComplete, Action onError)
            {
                if (client == null)
                    client = new WebClient();
    
                client.UploadDataCompleted += (s, e) =>
                {
                    if (e.Error == null && e.Result != null)
                    {
                        TResponse returnValue = default(TResponse);
    
                        try
                        {
                            string response = Encoding.UTF8.GetString(e.Result);
                            returnValue = JsonConvert.DeserializeObject(response);
                        }
                        catch (Exception ex)
                        {
                            onError(new JsonParseException(ex));
                        }
    
                        onComplete(returnValue);
                    }
                    else
                        onError(e.Error);
                };
    
                client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
                client.Encoding = System.Text.Encoding.UTF8;
    
                byte[] data = Encoding.UTF8.GetBytes(jsonData);
                client.UploadDataAsync(new Uri(url), "POST", data);
            }
        }
    

    Example usage

        /// 
        /// Determines whether this instance [can get result from service].
        /// 
        [Test]
        public void CanGetResultFromService()
        {
            string url = "http://httpbin.org/ip";
            Ip result;
    
            service.Get(url,
            success =>
            {
                result = success;
            },
            error =>
            {
                Debug.WriteLine(error.Message);
            });
    
            Thread.Sleep(5000);
        }
        /// 
        /// Determines whether this instance [can post result automatic service].
        /// 
        [Test]
        public void CanPostResultToService()
        {
            string url = "http://httpbin.org/post";
            string data = "{\"test\":\"hoi\"}";
            HttpBinResponse result = null;
    
            service.Post(url, data,
                response =>
                {
                    result = response;
                },
                error =>
                {
                    Debug.WriteLine(error.Message);
                });
    
            Thread.Sleep(5000);
        }
    }
    public class Ip
    {
        public string Origin { get; set; }
    }
    public class HttpBinResponse
    {
        public string Url { get; set; }
        public string Origin { get; set; }
        public Headers Headers { get; set; }
        public object Json { get; set; }
        public string Data { get; set; }
    }
    public class Headers
    {
        public string Connection { get; set; }
        [JsonProperty("Content-Type")]
        public string ContentType { get; set; }
        public string Host { get; set; }
        [JsonProperty("Content-Length")]
        public string ContentLength { get; set; }
    }
    

    Just to share some knowledge!

    Good luck!

提交回复
热议问题