C#post方法

post方法
using
System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Web; namespace Demo { public class MyPostGetHelper { public static string PostWebRequest(string postUrl, string paramData, Encoding dataEncode, string header = "") { string ret = string.Empty; try { if (dataEncode == null) dataEncode = Encoding.UTF8; byte[] byteArray = dataEncode.GetBytes(paramData); //转化 HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl)); webReq.Method = "POST"; webReq.ContentType = "application/json"; webReq.Headers.Add("Session-Key", header); webReq.ContentLength = byteArray.Length; Stream newStream = webReq.GetRequestStream(); newStream.Write(byteArray, 0, byteArray.Length);//写入参数 newStream.Close(); HttpWebResponse response = (HttpWebResponse)webReq.GetResponse(); var c = response.GetResponseStream(); StreamReader sr = new StreamReader(c, Encoding.UTF8); Char[] read = new Char[4000]; int count = sr.Read(read, 0, read.Length); while (count > 0) { String str = new String(read, 0, count); ret += str; count = sr.Read(read, 0, read.Length); } sr.Close(); response.Close(); newStream.Close(); } catch (Exception ex) { throw; } return ret; } } }

 

转载于:https://www.cnblogs.com/a735882640/p/7625638.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 C# 中发送 POST 请求并传递 JSON 数据,你可以使用 `HttpClient` 类来实现。以下是一个示例代码: ```csharp using System; using System.Net.Http; using System.Text; using System.Threading.Tasks; class Program { static async Task Main() { string url = "https://example.com/api/endpoint"; string json = "{\"name\":\"John\", \"age\":30}"; using (HttpClient client = new HttpClient()) { StringContent content = new StringContent(json, Encoding.UTF8, "application/json"); HttpResponseMessage response = await client.PostAsync(url, content); if (response.IsSuccessStatusCode) { string responseContent = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseContent); } else { Console.WriteLine($"Error: {response.StatusCode}"); } } } } ``` 在上述代码中,我们使用 `HttpClient` 类发送 POST 请求。首先,我们定义了要发送的 JSON 数据存储在 `json` 变量中。然后,我们创建了一个 `HttpClient` 对象,并使用 `PostAsync` 方法发送 POST 请求。我们将 JSON 数据作为字符串放入 `StringContent` 对象中,指定其编码和内容类型为 "application/json"。 如果请求成功,我们可以使用 `ReadAsStringAsync` 方法从响应中读取返回的内容。如果请求失败,我们输出错误状态码。 记得替换 `url` 变量为你要发送请求的目标 URL。另外,你可能需要引入 `System.Net.Http` 和 `System.Text` 命名空间。 这是一个基本的示例,你可以根据自己的需求进行调整。希望对你有所帮助!如果还有其他问题,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值