繁体   English   中英

使用C#(HTTPWEBREQUEST)返回丢失数据的JSON格式

[英]JSON format is being returned with missing data using C# (HTTPWEBREQUEST)

我正在使用JSON和C#(HttpWebRequest)。 基本上我有应用程序从API和API REST下载JSON,但问题是当我下载它时,JSON缺少一些数据,似乎是在削减一些数据,结构错误。 如果我使用的软件与我正在开发的软件相同,则不会发生此问题。 如果我遗漏了某些东西,我确信这与我的代码有关。 这是我的代码:

        var httpWebRequest = (HttpWebRequest)WebRequest.Create("MyURL");
        httpWebRequest.ContentType = "application/json";
        httpWebRequest.Method = "GET";
        string authInfo = "user" + ":" + "pass";
        authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
        httpWebRequest.Headers["Authorization"] = "Basic " + authInfo;


        // Create the HttpContent for the form to be posted.          

        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();


        using (var sr = new StreamReader(httpResponse.GetResponseStream(), Encoding.UTF8))
        {

            StreamWriter sw = new StreamWriter(@"C:\test\Stores.txt");

            sw.Write(sr.ReadToEnd());
        }

你可以试试这个。我的代码可以使用。

 public static async Task MethodName()
    {

        using (HttpClientHandler handler = new HttpClientHandler() { UseCookies = false })
        {
            using (HttpClient httpClient = new HttpClient(handler))
            {

                httpClient.DefaultRequestHeaders.Authorization = Program.getAuthenticationHeader();
                string filterQuery = Program.getURI().ToString();

                using (HttpResponseMessage httpResponse = await httpClient.GetAsync(filterQuery).ConfigureAwait(false))
                {

                    var streamContent = await httpResponse.Content.ReadAsStreamAsync();
                    FileStream fs = new FileStream("C:\test\Stores.Json", FileMode.Create);
                    streamContent.CopyTo(fs);
                    streamContent.Close();
                    fs.Close();

                }
            }
        }
    }

这可能是您的Http请求(GET)的问题。 步骤1 - 如果您有一个使用API​​的工作软件,请使用Fiddler分析它发送的http GET请求。 您还需要检查标题信息。 第2步 - 将Http请求与您创建的HttpRequest进行比较。 可能缺少参数等。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM