C# 通过 WebClient 上传 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11081760/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 16:24:40  来源:igfitidea点击:

Upload JSON via WebClient

c#jsonwebclient

提问by JavaScript Developer

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:

我有一个 Web 应用程序,它使用 JQuery 与我的后端进行交互。后端成功接受 JSON 数据。例如,我可以成功发送以下 JSON:

{ "id":1, "firstName":"John", "lastName":"Smith" }

I now have a Windows Phone app that must hit this backend. I need to pass this same JSON via a WebClient. Currently I have the following, but i'm not sure how to actually pass the JSON.

我现在有一个必须访问此后端的 Windows Phone 应用程序。我需要通过 WebClient 传递相同的 JSON。目前我有以下内容,但我不确定如何实际传递 JSON。

string address = "http://www.mydomain.com/myEndpoint;
WebClient myService = new WebClient();
utilityService.UploadStringCompleted += new UploadStringCompletedEventHandler(utilityService_UploadStringCompleted);
utilityService.UploadStringAsync(address, string.Empty);

Can someone tell me what I need to do?

有人可以告诉我我需要做什么吗?

采纳答案by JavaScript Developer

Figured it out. I was forgetting the following:

弄清楚了。我忘记了以下内容:

myService.Headers.Add("Content-Type", "application/json");

回答by Rob Angelier

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

虽然问题已经回答了,但我认为分享我基于 WebClient 的简单 JsonService 会很好:

Base class

基类

/// <summary>
/// Class BaseJsonService.
/// </summary>
public abstract class BaseJsonService
{
    /// <summary>
    /// The client
    /// </summary>
    protected WebClient client;

    /// <summary>
    /// Gets the specified URL.
    /// </summary>
    /// <typeparam name="TResponse">The type of the attribute response.</typeparam>
    /// <param name="url">The URL.</param>
    /// <param name="onComplete">The configuration complete.</param>
    /// <param name="onError">The configuration error.</param>
    public abstract void Get<TResponse>(string url, Action<TResponse> onComplete, Action<Exception> onError);
    /// <summary>
    /// Sends the specified URL.
    /// </summary>
    /// <typeparam name="TResponse">The type of the attribute response.</typeparam>
    /// <param name="url">The URL.</param>
    /// <param name="jsonData">The json data.</param>
    /// <param name="onComplete">The configuration complete.</param>
    /// <param name="onError">The configuration error.</param>
    public abstract void Post<TResponse>(string url, string jsonData, Action<TResponse> onComplete, Action<Exception> onError);
}

Service implementation

服务实现

/// <summary>
    /// Class JsonService.
    /// </summary>
    public class JsonService : BaseJsonService
    {
        /// <summary>
        /// Gets the specified URL.
        /// </summary>
        /// <typeparam name="TResponse">The type of the attribute response.</typeparam>
        /// <param name="url">The URL.</param>
        /// <param name="onComplete">The configuration complete.</param>
        /// <param name="onError">The configuration error.</param>
        public override void Get<TResponse>(string url, Action<TResponse> onComplete, Action<Exception> onError)
        {
            if (client == null)
                client = new WebClient();

            client.DownloadStringCompleted += (s, e) =>
            {
                TResponse returnValue = default(TResponse);

                try
                {
                    returnValue = JsonConvert.DeserializeObject<TResponse>(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));
        }
        /// <summary>
        /// Posts the specified URL.
        /// </summary>
        /// <typeparam name="TResponse">The type of the attribute response.</typeparam>
        /// <param name="url">The URL.</param>
        /// <param name="jsonData">The json data.</param>
        /// <param name="onComplete">The configuration complete.</param>
        /// <param name="onError">The configuration error.</param>
        public override void Post<TResponse>(string url, string jsonData, Action<TResponse> onComplete, Action<Exception> 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<TResponse>(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

示例用法

    /// <summary>
    /// Determines whether this instance [can get result from service].
    /// </summary>
    [Test]
    public void CanGetResultFromService()
    {
        string url = "http://httpbin.org/ip";
        Ip result;

        service.Get<Ip>(url,
        success =>
        {
            result = success;
        },
        error =>
        {
            Debug.WriteLine(error.Message);
        });

        Thread.Sleep(5000);
    }
    /// <summary>
    /// Determines whether this instance [can post result automatic service].
    /// </summary>
    [Test]
    public void CanPostResultToService()
    {
        string url = "http://httpbin.org/post";
        string data = "{\"test\":\"hoi\"}";
        HttpBinResponse result = null;

        service.Post<HttpBinResponse>(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!

祝你好运!