How to get json response using system.net.webrequest in c#?

前端 未结 2 1357
感动是毒
感动是毒 2020-12-12 15:36

I need to get json data from an external domain. I used webrequest to get the response from a website. Here\'s the code:

var request = WebRequest.Create(url)         


        
相关标签:
2条回答
  • 2020-12-12 15:57

    Some APIs want you to supply the appropriate "Accept" header in the request to get the wanted response type.

    For example if an API can return data in XML and JSON and you want the JSON result, you would need to set the HttpWebRequest.Accept property to "application/json".

    HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(requestUri);
    httpWebRequest.Method = WebRequestMethods.Http.Get;
    httpWebRequest.Accept = "application/json";
    
    0 讨论(0)
  • 2020-12-12 16:07

    You need to explicitly ask for the content type.

    Add this line:

     request.ContentType = "application/json; charset=utf-8";
    At the appropriate place

    0 讨论(0)
提交回复
热议问题