【问题标题】:Send JSON list via GET Request通过 GET 请求发送 JSON 列表
【发布时间】:2016-04-08 17:05:03
【问题描述】:

我正在尝试加快本地软件同步的过程。现在,我们为我们需要的每条记录发送一个 GET 请求,API 发送回一个包含该记录数据的 JSON 字符串,然后将其插入到本地数据库中。这一切都有效,但是它可能非常缓慢。我正在尝试加快速度,并希望一个好的方法是发送List<Dictionary<string, string>> 的 JSON。这样一来,我就可以在 API 端一次性请求更多数据,将其添加到列表中,然后将其作为 JSON 传递回本地机器。

我现在在本地:

Encoding enc = System.Text.Encoding.GetEncoding(1252);
using (HttpClient client = new HttpClient())
{
    string basicAuth = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", usr, pwd)));

    client.BaseAddress = new Uri(baseUrl);
    client.DefaultRequestHeaders.Clear();
    client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", basicAuth);
    client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
    string requested = JsonConvert.SerializeObject(tableList);

    HttpResponseMessage response = client.GetAsync(syncUrl + hash + "/" + requested).Result;

    if (!response.IsSuccessStatusCode)
    {
        // get the error
        StreamReader errorStream = new StreamReader(response.Content.ReadAsStreamAsync().Result, enc);
        throw new Exception(errorStream.ReadToEnd());
    }
}

我的控制器调用如下所示:

[System.Web.Http.AcceptVerbs("GET")]
[Route("getRecords/{hash}/{requested}")]
public HttpResponseMessage getRecords(string hash, string requested)

每当我进行此调用时,它都会给我一个错误,即它找不到 URI,我什至没有在我的 API 上命中断点。我该如何让它发挥作用,或者有更好的方法来完成我正在做的事情吗?

【问题讨论】:

  • 如果您不发布,您希望我们如何知道您传递的 Url 是否正确?

标签: c# json rest asp.net-mvc-5


【解决方案1】:

您需要对数据进行 urlencode,如果有任何特殊的 url 字符(如&符号或斜线),它将使数据无法使用,因此您必须对其进行 urlencode 以正确格式化。

使用类似...

string requested = Uri.EscapeDataString(JsonConvert.SerializeObject(tableList));

这将对特殊字符进行编码,以便它们可以安全地在 URL 上传输。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-17
    • 1970-01-01
    • 1970-01-01
    • 2020-09-15
    • 2011-11-04
    • 1970-01-01
    • 2021-05-23
    相关资源
    最近更新 更多