如何从http处理json

时间:2015-05-07 08:27:38

标签: c# json webclient

我使用WebClient类来寻找网站。它返回一个下载对话框,用于在json文件中下载输出。 Issit可以在不下载的情况下读取json文件中的内容吗?我打开了chrome并粘贴了相同的url,chrome在浏览器中显示了输出。

2 个答案:

答案 0 :(得分:1)

这取决于内容类型和浏览器,在某些情况下,内容可能是 压缩 。 Stackoverflow API就是这样一个例子。

在这些情况下,您需要设置request.AutomaticDecompression。下面的代码可能会让您对理解有所了解并从那里继续。

public string CallRequest(Uri url)
{
    var request = WebRequest.Create(url) as HttpWebRequest;
    var httpResponse = "";
    if (request != null)
    {
        request.UserAgent = "stackoverflow"; // just example.
        request.Accept = "gzip,deflate";
        request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

        using (var response = request.GetResponse() as HttpWebResponse)
        {           
            using (var responseStream = response.GetResponseStream())
            {
                var reader = new StreamReader(responseStream);
                httpResponse = reader.ReadToEnd();
            }
        }
    }

    return httpResponse;
}   

答案 1 :(得分:0)

只需向链接发出请求即可获得字符串中的JSON:

public static Response MakeRequest(string requestUrl){
try
{
    HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;
    using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
    {
        if (response.StatusCode != HttpStatusCode.OK)
            throw new Exception(String.Format(
            "Server error (HTTP {0}: {1}).",
            response.StatusCode,
            response.StatusDescription));
        DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(Response));
        object objResponse = jsonSerializer.ReadObject(response.GetResponseStream());
        Response jsonResponse
        = objResponse as Response;
        return jsonResponse;
    }
}
catch (Exception e)
{
    Console.WriteLine(e.Message);
    return null;
}

}