0

我正在尝试使用Refit将数据作为x-www-form-urlencoded发送到 api 。但由于某种原因,没有检索到响应。我一步一步地遵循了许多教程,但没有任何效果。可能是什么问题?提前致谢。

要求:

public class SynchronizerApiRequest
    {
        public SynchronizerApiRequest() { }

        [JsonProperty("username")]
        public string Username { get; set; }

        [JsonProperty("password")]
        public string Password { get; set; }

        [JsonProperty("last_sync_date")]
        public string LastSyncDate { get; set; }
    }

回复:

public class SynchronizerApiResponse
{
    public SynchronizerApiResponse() { }

    [JsonProperty("success")]
    public bool Success { get; set; }
    
    [JsonProperty("tables")]
    public SyncData Tables { get; set; }
}

同步数据:

    public class SyncData
{
    [JsonProperty("hometab")]
    public List<HomeTab> HomeTabs { get; set; }

    [JsonProperty("category")]
    public List<Category> Categories { get; set; }

    [JsonProperty("doaa")]
    public List<Doaa> Doaas { get; set; }

    [JsonProperty("hijri")]
    public List<Hijri> Hijris { get; set; }

    [JsonProperty("hijri_events")]
    public List<Hijri> HijriEvents { get; set; }
}

界面:

public interface ISynchronizer
    {
        [Post("/action.php?fn=sync")]
        Task<SynchronizerApiResponse> Request([Body(BodySerializationMethod.UrlEncoded)] SynchronizerApiRequest request);
    }

最后是我调用 api 的代码:

public async Task<SynchronizerApiResponse> GetAllData()
    {
        SynchronizerApiRequest request = new SynchronizerApiRequest()
        {
            Username = "***",
            Password = "***",
            LastSyncDate = Methods.IsEmpty(Methods.GetAppProperty(Constants.LAST_SYNC_DATE)) ? ""
                                  : Methods.GetAppProperty(Constants.LAST_SYNC_DATE)
        };

        syncrhonizer = RestService.For<ISynchronizer>(Constants.BASE_ADDRESS);

        SynchronizerApiResponse response = await syncrhonizer.Request(request);

        System.Diagnostics.Debug.Write(">>>>>>>>>>>>>>>>>>>>>>>>>>>>." + response.Success + " " + response.Tables.HomeTabs.Count);
        return response;

    }
4

1 回答 1

0

所以我使用了 newtonsoft json 并且它有效。解决方案是知道如何发送您的参数,即以哪种形式发送。以下是我的解决方案:

string parameters = "username=X&password=Y&last_sync_date=2020-01-01";

// serialize object to json
var content = new StringContent(parameters, Encoding.UTF8, "application/x-www-form-urlencoded");
var response = await Client.PostAsync(Constants.GET_ALL_DATA_URI, content);
string clientresult = response.Content.ReadAsStringAsync().Result;
response.EnsureSuccessStatusCode();

var json = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<SynchronizerApiResponse>(json);
于 2021-05-26T21:07:08.533 回答