C# (VS2015) 用HttpWebRequest get 方式 与 post 方式

C# (VS2015) 用HttpWebRequest对象 get 方式 与 post 方式 连接 测试用的代码怎样写,谢谢

/*
*  url:POST请求地址
*  postData:json格式的请求报文,例如:{"key1":"value1","key2":"value2"}
*/
public static string PostUrl(string url, string postData)
{
    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
    req.Method = "POST";
    req.TimeOut = "800";//设置请求超时时间,单位为毫秒
    req.ContentType = "application/json";
    byte[] data = Encoding.UTF8.GetBytes(postData);
    req.ContentLength = data.Length;

    using (Stream reqStream = req.GetRequestStream())
    {
        reqStream.Write(data, 0, data.Length);
        reqStream.Close();
    }

    HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
    Stream stream = resp.GetResponseStream();

    //获取响应内容
    string result = "";
    using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
    {
        result = reader.ReadToEnd();
    }
    return result;
}


```c++


```

该回答参考ChatGPT:
以下是C# (VS2015)中使用HttpWebRequest对象进行GET和POST请求的示例代码:
GET请求:

using System.IO;
using System.Net;

namespace HttpWebRequestDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            // 目标URL
            string url = "https://www.example.com";
            // 创建HttpWebRequest对象
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            // 发送GET请求
            request.Method = "GET";
            // 获取响应
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            // 读取响应内容
            Stream stream = response.GetResponseStream();
            StreamReader reader = new StreamReader(stream);
            string result = reader.ReadToEnd();
            // 输出响应内容
            Console.WriteLine(result);
            // 关闭资源
            reader.Close();
            stream.Close();
            response.Close();
        }
    }
}

POST请求:

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

namespace HttpWebRequestDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            // 目标URL
            string url = "https://www.example.com";
            // 创建HttpWebRequest对象
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            // 发送POST请求
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            // 构造POST请求参数
            string postData = "username=test&password=123456";
            byte[] postDataBytes = Encoding.UTF8.GetBytes(postData);
            request.ContentLength = postDataBytes.Length;
            Stream requestStream = request.GetRequestStream();
            requestStream.Write(postDataBytes, 0, postDataBytes.Length);
            requestStream.Close();
            // 获取响应
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            // 读取响应内容
            Stream stream = response.GetResponseStream();
            StreamReader reader = new StreamReader(stream);
            string result = reader.ReadToEnd();
            // 输出响应内容
            Console.WriteLine(result);
            // 关闭资源
            reader.Close();
            stream.Close();
            response.Close();
        }
    }
}

该回答引用ChatGPT:以下是C#中使用HttpWebRequest对象进行GET和POST请求的示例代码:

GET请求示例:

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

public class HttpWebRequestGETExample
{
    public static void Main()
    {
        // 目标URL
        string url = "http://example.com/api/data";

        // 创建HttpWebRequest对象
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

        // 设置请求方法
        request.Method = "GET";

        // 发送请求并获取响应
        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        {
            // 读取响应数据
            using (StreamReader reader = new StreamReader(response.GetResponseStream()))
            {
                string responseText = reader.ReadToEnd();
                Console.WriteLine(responseText);
            }
        }
    }
}

POST请求示例:

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

public class HttpWebRequestPOSTExample
{
    public static void Main()
    {
        // 目标URL
        string url = "http://example.com/api/data";

        // POST请求参数
        string postData = "param1=value1&param2=value2";

        // 将POST请求参数转换为字节数组
        byte[] data = Encoding.UTF8.GetBytes(postData);

        // 创建HttpWebRequest对象
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

        // 设置请求方法和Content-Type
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = data.Length;

        // 将POST请求参数写入请求流中
        using (Stream requestStream = request.GetRequestStream())
        {
            requestStream.Write(data, 0, data.Length);
        }

        // 发送请求并获取响应
        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        {
            // 读取响应数据
            using (StreamReader reader = new StreamReader(response.GetResponseStream()))
            {
                string responseText = reader.ReadToEnd();
                Console.WriteLine(responseText);
            }
        }
    }
}

这些示例代码使用的是.NET Framework中的HttpWebRequest对象。如果你使用的是.NET Core,则应该使用HttpClient对象进行HTTP请求。

基于最新版ChatGPT4的回答,望采纳!!!有其他问题也可以询问我哦、”(最新版更智能,功能更加强大)

以下是 C# (VS2015) 中使用 HttpWebRequest 对象进行 GET 和 POST 请求的示例代码:

使用 GET 请求:

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

namespace HttpWebRequestExample
{
    class Program
    {
        static void Main(string[] args)
        {
            string url = "https://example.com/api/data?param1=value1&param2=value2";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            request.ContentType = "application/json";

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (Stream responseStream = response.GetResponseStream())
            {
                StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.UTF8);
                string responseText = reader.ReadToEnd();
                Console.WriteLine(responseText);
            }
        }
    }
}

使用 POST 请求:

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

namespace HttpWebRequestExample
{
    class Program
    {
        static void Main(string[] args)
        {
            string url = "https://example.com/api/data";
            string postData = "{\"param1\":\"value1\",\"param2\":\"value2\"}";
            byte[] postDataBytes = Encoding.UTF8.GetBytes(postData);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/json";
            request.ContentLength = postDataBytes.Length;

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

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (Stream responseStream = response.GetResponseStream())
            {
                StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.UTF8);
                string responseText = reader.ReadToEnd();
                Console.WriteLine(responseText);
            }
        }
    }
}

在这些示例代码中,url 是请求的URL地址,postData 是要发送的POST请求数据。在GET请求中,参数可以通过URL地址传递;在POST请求中,需要将参数序列化成JSON格式,并发送到请求体中。根据实际情况修改URL地址和请求参数即可。

GET 请求:

using System;
using System.IO;
using System.Net;
class Program
{
    static void Main(string[] args)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://example.com/api/data");
        request.Method = "GET";
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        Stream stream = response.GetResponseStream();
        StreamReader reader = new StreamReader(stream);
        string content = reader.ReadToEnd();
        Console.WriteLine(content);
    }
}

POST 请求:

using System;
using System.IO;
using System.Net;
using System.Text;
class Program
{
    static void Main(string[] args)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://example.com/api/data");
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        string postData = "param1=value1&param2=value2";
        byte[] dataBytes = Encoding.UTF8.GetBytes(postData);
        request.ContentLength = dataBytes.Length;
        Stream requestBody = request.GetRequestStream();
        requestBody.Write(dataBytes, 0, dataBytes.Length);
        requestBody.Close();
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        Stream stream = response.GetResponseStream();
        StreamReader reader = new StreamReader(stream);
        string content = reader.ReadToEnd();
        Console.WriteLine(content);
    }
}

不知道你说的测试代码是什么,是服务器还是客户端
是测试你的代码是否正确返回,还是你不明白HttpWebRequest调用?

该回答引用ChatGPT
使用HttpWebRequest对象进行GET和POST请求的代码如下:
GET请求:
csharp
string url = "http://www.example.com/api/data";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string result = string.Empty;
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
result = reader.ReadToEnd();
}

POST请求:
csharp
string url = "http://www.example.com/api/data";
string postData = "param1=value1¶m2=value2";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
using (Stream stream = request.GetRequestStream())
{
stream.Write(byteArray, 0, byteArray.Length);
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string result = string.Empty;
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
result = reader.ReadToEnd();
}

在GET请求中,我们首先创建一个HttpWebRequest对象,设置请求的URL和请求方法为GET。然后使用GetResponse方法获取响应,并使用StreamReader读取响应流中的数据。
在POST请求中,我们首先创建一个HttpWebRequest对象,设置请求的URL和请求方法为POST。然后设置请求的ContentType为application/x-www-form-urlencoded,并将POST数据转换为字节数组,设置请求的ContentLength为字节数组的长度。接着使用GetRequestStream方法获取请求流,并将POST数据写入请求流中。最后使用GetResponse方法获取响应,并使用StreamReader读取响应流中的数据。

以下是C#HttpWebRequest 测试代码,在button按钮点击时间下触发测试,Console.WriteLine(postResult);控制台输出测试结果


private void button1_Click_1(object sender, EventArgs e)
        {
            //测试get方式连接
            string getUrl = "http://www.example.com/api/getdata?id=123";
            HttpWebRequest getRequest = (HttpWebRequest)WebRequest.Create(getUrl);
            getRequest.Method = "GET";
            HttpWebResponse getResponse = (HttpWebResponse)getRequest.GetResponse();
            StreamReader getReader = new StreamReader(getResponse.GetResponseStream());
            string getResult = getReader.ReadToEnd();
            Console.WriteLine(getResult);

            //测试post方式连接
            string postUrl = "http://www.example.com/api/postdata";
            HttpWebRequest postRequest = (HttpWebRequest)WebRequest.Create(postUrl);
            postRequest.Method = "POST";
            string postData = "id=123&name=John";
            byte[] postBytes = System.Text.Encoding.UTF8.GetBytes(postData);
            postRequest.ContentType = "application/x-www-form-urlencoded";
            postRequest.ContentLength = postBytes.Length;
            Stream postStream = postRequest.GetRequestStream();
            postStream.Write(postBytes, 0, postBytes.Length);
            postStream.Close();
            HttpWebResponse postResponse = (HttpWebResponse)postRequest.GetResponse();
            StreamReader postReader = new StreamReader(postResponse.GetResponseStream());
            string postResult = postReader.ReadToEnd();
            Console.WriteLine(postResult);

            Console.ReadLine();
        }

HttpWebRequest 其他人代码也提供了。 个人更喜欢httpclient 代码更简洁

HttpClient http=new HttpClient();
http.DefaultRequestHeaders.Add("UserAgent", "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko");
var httpContent = new StringContent("文本")
http.PostAsync("http://127.0.0.1/testapi",httpContent );//Post请求
http.GetAsync("http://127.0.0.1/testapi");//Get请求

以下答案由GPT-3.5大模型与博主波罗歌共同编写:
以下是使用HttpWebRequest对象实现get和post请求的示例代码:

使用GET方式发送请求:

```csharp
string url = "https://w/

谢谢! 如用http的post发送JSON格式的报文,如图片内容

img

img


要怎么发送呢,

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

namespace HttpWebRequestDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.example.com/api?key=value");
            request.Method = "GET";
            request.ContentType = "application/json";

            HttpWebResponse response = null;
            StreamReader reader = null;

            try
            {
                response = (HttpWebResponse)request.GetResponse();
                reader = new StreamReader(response.GetResponseStream());
                string responseText = reader.ReadToEnd();
                Console.WriteLine(responseText);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
                if (response != null)
                {
                    response.Close();
                }
            }
        }
    }
}

POST请求

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

namespace HttpWebRequestDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.example.com/api");
            request.Method = "POST";
            request.ContentType = "application/json";

            string requestBody = "{\"key\":\"value\"}";
            byte[] byteData = Encoding.UTF8.GetBytes(requestBody);
            request.ContentLength = byteData.Length;

            Stream requestStream = request.GetRequestStream();
            requestStream.Write(byteData, 0, byteData.Length);
            requestStream.Close();

            HttpWebResponse response = null;
            StreamReader reader = null;

            try
            {
                response = (HttpWebResponse)request.GetResponse();
                reader = new StreamReader(response.GetResponseStream());
                string responseText = reader.ReadToEnd();
                Console.WriteLine(responseText);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
                if (response != null)
                {
                    response.Close();
                }
            }
        }
    }
}
  1. 在GET请求中,在Url中直接加上查询参数即可。
  2. 在POST请求中,需要将请求体编码成字节数组并设置到HttpWebRequest对象的ContentLength属性中,然后向请求流中写入字节数组。FGPT