Web Service without adding a reference?

前端 未结 6 783
眼角桃花
眼角桃花 2020-12-04 16:16

I have 3 web services added to service references in a class library.(This is a sample project for an API use) I need to move these into my project but i ca

6条回答
  •  遥遥无期
    2020-12-04 16:49

    Here's an example of how to call a "GET" web service from your C# code:

    public string CallWebService(string URL)
    {
        HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(URL);
        objRequest.Method = "GET";
        objRequest.KeepAlive = false;
    
        HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
        string result = "";
        using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
        {
            result = sr.ReadToEnd();
            sr.Close();
        }
        return result;
    }
    

    Simply pass it a URL, and it'll return a string containing the response. From there, you can call the JSON.Net "DeserializeObject" function to turn the string into something useful:

    string JSONresponse = CallWebService("http://www.inorthwind.com/Service1.svc/getAllCustomers");
    
    List customers = JsonConvert.DeserializeObject>(JSONresponse);
    

    Hope this helps.

提交回复
热议问题