【问题标题】:how to add body in post request c# [duplicate]如何在发布请求c#中添加正文[重复]
【发布时间】:2021-10-23 14:07:53
【问题描述】:

我,尝试将 body 放入请求中,但实际上并没有奏效, 在正文中我想输入 json 格式 {"ClaimNo":"123123"}

我已将其用作代码:

    string ClaimStatus_url  = "https:xyz";
     WebRequest request = WebRequest.Create(ClaimStatus_url);
     request.ContentType = "application/json";
     request.Method = "POST";
     //request.Headers = "";// i used this for puting body in it but did not work
     WebResponse response = request.GetResponse();
     Stream responseStream = response.GetResponseStream();
     StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
     string result = reader.ReadToEnd();

 
 
 

【问题讨论】:

标签: c#


【解决方案1】:
using System.Text;
using System.Text.Json;

namespace TestPostData;

public class Data
{
    public int ClaimNo { get; set; }
}

public static class Program
{
    public static void Main()
    {
        var postData = new Data
        {
            ClaimNo = 123123,
        };

        var client = new System.Net.Http.HttpClient();

        var content = new StringContent(JsonSerializer.Serialize(postData), Encoding.UTF8, "application/json");

        var response = client.PostAsync("https:xyz", content).Result;
    }
}

这是一个使用 HttpClient 类的示例,现在推荐使用 WebRequest。

【讨论】:

    【解决方案2】:

    试试这个,我希望它会工作。

     var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx");
    
    var postData = "thing1=" + Uri.EscapeDataString("hello");
        postData += "&thing2=" + Uri.EscapeDataString("world");
    var data = Encoding.ASCII.GetBytes(postData);
    
    request.Method = "POST";
    request.ContentType = "application/x-www-form-urlencoded";
    request.ContentLength = data.Length;
    
    using (var stream = request.GetRequestStream())
    {
        stream.Write(data, 0, data.Length);
    }
    
    var response = (HttpWebResponse)request.GetResponse();
    
    var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
    

    【讨论】:

    • 他想使用 JSON 发送正文,因此您必须更改内容类型和 postdata 字符串
    【解决方案3】:

    我将从使用 RestSharp 开始。

    dotnet add package RestSharp
    

    然后我将创建一个 DTOS 对象,其中包含您要在 json 中发送的内容:

    public class DtosObject
    {
        public string ClaimNo {get; set;}
    }
    

    然后将其作为对象传入(我会将类称为与它包含的数据相关的东西)。如果你只使用 ClaimNo,你也可以像这样使用 KeyValuePair:

    var body = new KeyValuePair<string, string>("ClaimNo", "123123");
    

    然后你可以像这样发送请求:

    public async Task<IRestResult> PostAsync(string url, object body)
    {
        var client = new RestClient(url);
        client.Timeout = -1;
    
        var request = new RestRequest(Method.Post);
        request.AddJsonBody(body);
    
        var response = await client.ExecuteAsync(request);
        return response;
    }
    

    【讨论】:

      【解决方案4】:
                        string ClaimStatus_url  = "https://qms.xyz.in/FGClaimWsAPI/api/Common/FetchClaimdetails";
      
                                              var httpWebRequest = (HttpWebRequest)WebRequest.Create(ClaimStatus_url);
                                              httpWebRequest.ContentType = "application/json";
                                              httpWebRequest.Method = "POST";
                                              using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                                              {
                                                  string json = "{\"ClaimNo\":\""+ userProfile.ClaimNumber +"\"}";
                                                  //string json = "{\"ClaimNo\":\"CV010831\"}";
                                                  //await turnContext.SendActivityAsync(MessageFactory.Text(json, json), cancellationToken);
                                                  streamWriter.Write(json);
                                              }
                                              var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                                              var result1 = "" ;
                                              using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                                              {
                                                  var result = streamReader.ReadToEnd();
                                                  result1 = result.Substring(1, result.Length -2); // to bring response result in proper format
                                                                                                   
      
                                              }
      
                                              _claimstaus = GenrateJSON_Claim(result1);
      

      上面的代码有效

      【讨论】:

      • 请添加更多详细信息以扩展您的答案,例如工作代码或文档引用。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-18
      • 1970-01-01
      • 2019-09-24
      • 2015-12-22
      • 1970-01-01
      • 2023-03-18
      相关资源
      最近更新 更多