ASP.NET MVC - Using cURL or similar to perform requests in application

前端 未结 4 1937
一整个雨季
一整个雨季 2021-02-01 11:06

I\'m building an application in ASP.NET MVC (using C#) and I would like to know how I can perform calls like curl http://www.mywebsite.com/clients_list.xml inside my controller

4条回答
  •  伪装坚强ぢ
    2021-02-01 11:42

    Example code using HttpWebRequest and HttpWebResponse :

    public string GetResponseText(string url) {
        string responseText = String.Empty;
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = "GET";
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        using (StreamReader sr = new StreamReader(response.GetResponseStream())) {
            responseText = sr.ReadToEnd();
        }
        return responseText;
    }
    

    To POST data :

    public string GetResponseText(string url, string postData) {
        string responseText = String.Empty;
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = "POST";
        request.ContentLength = postData.Length;
        using (StreamWriter sw = new StreamWriter(request.GetRequestStream())) {
            sw.Write(postData);
        }
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        using (StreamReader sr = new StreamReader(response.GetResponseStream())) {
            responseText = sr.ReadToEnd();
        }
        return responseText;
    }
    

提交回复
热议问题