Web request Content type is always text/html

风流意气都作罢 提交于 2020-01-11 11:28:11

问题


I have a web api I need to use. This api will return the data according the content type I'm sending. Normally it will return html response. If the request has Content-Type header with the 'application/json' header it will return a json response.

When I try it using Postman and adding the content-type header (as application/json) everything is good. But when trying it using C# WebRequest object I'm always getting the html response regardless the content-type header I'm using. I've used fiddler to see the web request, and the content type is always text/html.

Here is my code. Tried this one:

    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;

Also tried this one:

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();
                    }
            }

Still, every time, the content type is text/html.

Thanks in advance, Shaul


回答1:


What you want to do is set the Accept headers, not Content-Type. Accept specifies the types of data you want to receive. Content-Type is for specifying the type of data you're sending.

httpWebRequest.Accept = "application/json";


来源:https://stackoverflow.com/questions/35803815/web-request-content-type-is-always-text-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!