使用Postman从API检索的数据与使用C#程序时不同

kfgdxczn  于 4个月前  发布在  Postman
关注(0)|答案(1)|浏览(75)

我使用Postman从Sigfox API检索的数据与我使用C#程序使用HTTP客户端时获得的数据不同。
API包含查询参数,例如:

  • limit=(a number)--限制我可以接收的消息数量的数字(不影响问题)

  • before =(unix time)
  • since=(unix time)是时间参数。

在postman中,我收到的数据遵循时间参数,这意味着收到的数据是在设定时间之前和设定时间之后。
API链接(含假信息):https://backend.sigfox.com/api/devicetypes/devicetpes-id(filler)/messages?limit=100&before=1568186400&since=1568185800
这是数据的下载部分:

public static class DownloadData
{
    private static string UrlParameters="?limit=100&before=&since=";
    public static void GetfromAPI(string deviceId, long beforeTime, long sinceTime)
    {
        var apiResponse = new Models.Datas();
        var baseUrl = ConfigurationManager.AppSettings["ApiBaseUrl"];
        var username = ConfigurationManager.AppSettings["ApiUserName"];
        var password = ConfigurationManager.AppSettings["ApiPassword"];
        var mediatype = ConfigurationManager.AppSettings["MediaType"];
        var finalUrl = string.Format(baseUrl, deviceId, beforeTime, sinceTime);
        using (var client = new ApiClient(finalUrl, username, password, mediatype))
        {
            //apiResponse = client.GetAsyncMessage<Models.Datas>(UrlParameters).Result;
            apiResponse = client.GetAsyncMessage<Models.Datas>(UrlParameters).Result;
            InsertToDatabase(FormatData(apiResponse.Data)); //apiresponse.data is holding the data

        }
    }

字符串
http客户端

public class ApiClient : IDisposable
{
    private HttpClient _httpClient;
    private readonly string _baseurl;
    private readonly string _username;
    private readonly string _password;
    private readonly string _mediatype;

    public ApiClient(string baseurl, string username, string password , string mediatype)
    {
        _baseurl = baseurl;
        _username = username;
        _password = password;
        _mediatype = mediatype;
    }

    public async Task<TResult> GetAsyncMessage<TResult>(string url) where TResult : class, new()

    {
        var strResponse = await GetAsyncMessage(url);


        return JsonConvert.DeserializeObject<TResult>(strResponse, new JsonSerializerSettings ///str respons holding the string 
        {
            ContractResolver = new CamelCasePropertyNamesContractResolver()
        });
    }

    private async Task<string> GetAsyncMessage(string url)
    {
        CheckHttpClientConnection();

        using (var response = await _httpClient.GetAsync(url))
        {
            response.EnsureSuccessStatusCode();
            return await response.Content.ReadAsStringAsync();

        }
    }


httpclientwith basic auth

private void CreateHttpClient()
    {
        _httpClient = new HttpClient { BaseAddress = new Uri(_baseurl) };
        byte[] cred = UTF8Encoding.UTF8.GetBytes(_username + ":" + _password);
        _httpClient.DefaultRequestHeaders.Authorization =
            new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(cred));
        _httpClient.DefaultRequestHeaders.Accept.Add(
            new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue(_mediatype));
    }


运行顶层代码的另一个文件中的FUNCTION

DownloadData.GetfromAPI("devicetypesid filler",Common.BCurrenttimetoUnix(), Common.SCurrenttimetoUnix());

the common.bcurrentimetounix etc is taking the value from the function as the before and since query parameters.


所以我在postman中得到的数据遵循查询参数。这意味着我得到的数据是在before和since时间跨度中。
举例说明:
before:4.50pm因为4.40pm是为params设置的时间。
检索到的数据为第1个数据= 4.49pm,第100个数据= 4.41pm。
然而,在我的C#程序中,它甚至不遵循参数。检索的数据超过since和before计时。
编辑#1.图片
x1c 0d1x的数据

编辑#2

BASEURL:

<add key="ApiBaseUrl" value="https://api.sigfox.com/v2/device-types/{0}/messages" />

编辑#3

使用此作为baseurl:


<add key="ApiBaseUrl"  value="https://api.sigfox.com/v2/device-types/{0}/messages?limit=100&amp;before={1}&amp;since={2}" />

编辑#4

这个代码正在工作。

public static void GetfromAPI(string deviceId, long beforeTime, long sinceTime)
        {
            var apiResponse = new Models.Datas();
            var baseUrl = ConfigurationManager.AppSettings["ApiBaseUrl"];
            var username = ConfigurationManager.AppSettings["ApiUserName"];
            var password = ConfigurationManager.AppSettings["ApiPassword"];
            var mediatype = ConfigurationManager.AppSettings["MediaType"];
            var urlparam = ConfigurationManager.AppSettings["ApiParam"];
                
            var finalurl = string.Format(baseUrl, deviceId);
            var urlParam = $"?limit=100&before={beforeTime}&since={sinceTime}";

            using (var client = new ApiClient(finalurl, username, password, mediatype))
            {
                //apiResponse = client.GetAsyncMessage<Models.Datas>(UrlParameters).Result;
                apiResponse = client.GetAsyncMessage<Models.Datas>(urlParam).Result;
                InsertToDatabase(FormatData(apiResponse.Data)); //apiresponse.data is holding the data

            }

inn6fuwd

inn6fuwd1#

您正在设置您的UrlParameters变量,而没有beforesince的值:-

private static string UrlParameters="?limit=100&before=&since=";

字符串
在发送之前,你没有更新它;在设置finalUrl的地方,你的string.Format没有引用UrlParameters;因此,你得到的值超出了你指定的beforeTimeafterTime
目前还不清楚您使用的是什么ApiClient,但是,这里有一个使用基本WebClient的示例:

var baseUrl = "https://backend.sigfox.com/api/devicetypes";
var deviceId = "12345";
var before = 1568186400;
var since = 1568185800;

var url = $@"{baseUrl}/{deviceId}/messages?limit=100&before={before}&since={since}";

var json = new System.Net.WebClient().DownloadString(url);

已编辑

尝试像这样更新GetfromAPI方法(我已经修复了finalUrl的构造方式,并将其传递给GetAsyncMessage方法,而不是UrlParameters,我将baseUrl而不是finalUrl传递给ApiClient构造函数):

public static class DownloadData
{
    public static void GetfromAPI(string deviceId, long beforeTime, long sinceTime)
    {
        var apiResponse = new Models.Datas();
        var baseUrl = ConfigurationManager.AppSettings["ApiBaseUrl"];
        var username = ConfigurationManager.AppSettings["ApiUserName"];
        var password = ConfigurationManager.AppSettings["ApiPassword"];
        var mediatype = ConfigurationManager.AppSettings["MediaType"];

        var finalUrl = $"api/devicetypes/{deviceId}/messages?limit=100&before={beforeTime}&since={sinceTime}";

        using (var client = new ApiClient(baseUrl, username, password, mediatype))
        {
            apiResponse = client.GetAsyncMessage<Models.Datas>(finalUrl).Result;
            InsertToDatabase(FormatData(apiResponse.Data)); //apiresponse.data is holding the data
        }
    }
}


注意事项:您可能需要根据您的baseUrl设置来调整finalUrl(我在这里看不到);想法是在将url值传递给HttpClient之前检查它,以便您可以确认它试图获取的内容。

相关问题