Skip to main content
 首页 » 编程设计

c#之Web 请求内容类型总是 text/html

2024年01月31日23jyk

我有一个网络 API 需要使用。 此 api 将根据我发送的内容类型返回数据。 通常它会返回 html 响应。 如果请求具有带有“application/json” header 的 Content-Type header ,它将返回一个 json 响应。

当我尝试使用 Postman 并添加内容类型 header (如 application/json)时,一切都很好。 但是当使用 C# WebRequest 对象尝试它时,无论我使用的是什么内容类型 header ,我总是得到 html 响应。 我用fiddler看web请求,content type一直是text/html。

这是我的代码。 试过这个:

    var webAddr = "https://xxxxxxxx.com/api/blabla"; 
        var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr); 
        httpWebRequest.Method = "GET"; 
 
        httpWebRequest.Headers.Add("Authorization", "Basic xxxxxxxxxxx=="); 
        httpWebRequest.ContentType = "application/json; charset=utf-8"; 
 
        HttpWebResponse response = (HttpWebResponse)httpWebRequest.GetResponse(); 
 
 
        Stream resStream = response.GetResponseStream(); 
        using (var reader = new StreamReader(resStream)) 
        { 
            result = reader.ReadToEnd(); 
        } 
        txtResult.Text = result; 

也试过这个:

var request = (HttpWebRequest)WebRequest.Create(EndPoint + parameters); 
 
        request.Method = Method.ToString(); 
        request.ContentLength = 0; 
        request.ContentType = "application/json"; 
 
            String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(userName + ":" + password)); 
            request.Headers.Add("Authorization", "Basic " + encoded); 
 
 
 
        using (var response = (HttpWebResponse)request.GetResponse()) 
        { 
            var responseValue = string.Empty; 
 
            if (response.StatusCode != HttpStatusCode.OK) 
            { 
                var message = String.Format("Request failed. Received HTTP {0}", response.StatusCode); 
                return null; 
            } 
 
            // grab the response 
            using (var responseStream = response.GetResponseStream()) 
            { 
                if (responseStream != null) 
                    using (var reader = new StreamReader(responseStream)) 
                    { 
                        responseValue = reader.ReadToEnd(); 
                    } 
            } 

仍然,每次内容类型都是文本/html。

提前致谢, 沙乌尔

请您参考如下方法:

您要做的是设置Accept header ,而不是Content-Type。 Accept 指定您要接收的数据类型。 Content-Type 用于指定您发送的数据类型。

httpWebRequest.Accept = "application/json";