2012-06-18 6 views
7

У меня есть веб-приложение, в котором используется JQuery для взаимодействия с моим бэкэнд. Бэкэнд успешно принимает данные JSON. Например, я могу успешно отправить следующий JSON:Загрузить JSON через WebClient

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

У меня теперь есть приложение для Windows Phone, которое должно ударить по этому серверу. Мне нужно передать этот JSON через WebClient. В настоящее время у меня есть следующее, но я не уверен, как фактически передать JSON.

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

Может кто-нибудь сказать мне, что мне нужно сделать?

+0

Стандартный способ для небольших данных JSON, который не изменяет вашу сторону сервера данных, - это просто добавить их в качестве параметра URL-адреса, который вы вызываете в GET. В других случаях вы можете отправить их в POST в теле вашего запроса. –

+0

Что вы подразумеваете под «отправкой их в POST в теле вашего запроса»? Как вы это делаете с помощью WebClient? –

ответ

11

Выяснил это. Я забывал следующее:

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

Позвольте мне добавить эту строку, это также очень важно для сообщений с не-английскими языками 'client.Encoding = System.Text.Encoding.UTF8; ' Это то, чего не хватало в моем случае. – JohnPan

14

Хотя вопрос уже ответил, я подумал, что было бы неплохо, чтобы поделиться простой JsonService, основанный на WebClient:

Базовый класс

/// <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); 
} 

Внедрение обслуживания

/// <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); 
     } 
    } 

Пример использования

/// <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; } 
} 

Просто поделиться некоторыми знаниями!

Удачи вам!

Смежные вопросы