温馨提示×

c# webrequest如何使用

c#
小樊
81
2024-11-23 05:13:12
栏目: 编程语言

在C#中,你可以使用WebRequest类来发送HTTP请求并获取响应。以下是一个简单的示例,展示了如何使用WebRequest类发起GET和POST请求:

using System;
using System.IO;
using System.Net;
using System.Text;

class Program
{
    static void Main()
    {
        // 发起GET请求
        string getResponse = GetRequest("https://api.example.com/data");
        Console.WriteLine("GET Response: " + getResponse);

        // 发起POST请求
        string postData = "key1=value1&key2=value2";
        string postResponse = PostRequest("https://api.example.com/data", postData);
        Console.WriteLine("POST Response: " + postResponse);
    }

    static string GetRequest(string url)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = "GET";
        request.ContentType = "application/json";

        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
        {
            return reader.ReadToEnd();
        }
    }

    static string PostRequest(string url, string data)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";

        byte[] postDataBytes = Encoding.ASCII.GetBytes(data);
        request.ContentLength = postDataBytes.Length;

        using (Stream stream = request.GetRequestStream())
        {
            stream.Write(postDataBytes, 0, postDataBytes.Length);
        }

        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
        {
            return reader.ReadToEnd();
        }
    }
}

在这个示例中,我们定义了两个方法:GetRequestPostRequestGetRequest方法用于发起GET请求,而PostRequest方法用于发起POST请求。这两个方法都接受一个URL参数,并返回响应的字符串。

GetRequest方法中,我们创建了一个HttpWebRequest对象,并设置了请求方法为"GET"。然后,我们使用GetResponse方法获取响应,并使用StreamReader读取响应内容。

PostRequest方法中,我们首先将POST数据转换为字节数组,然后设置请求的内容类型为"application/x-www-form-urlencoded"。接下来,我们使用GetRequestStream方法获取请求的流,并将POST数据写入流中。最后,我们使用GetResponseStreamReader读取响应内容。

0