HttpClient API Post Refactor Code [英] HttpClient API Post Refactor Code

查看:57
本文介绍了HttpClient API Post Refactor Code的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hello All,


我想重构这段代码,以便使用HttpClient对象进行web api post call。


< pre class ="prettyprint"> public class SalesforceAccount
{


public string Name {get;组; }
public string AccountNumber {get;组; }

}

var acct = new SalesforceAccount();
acct.Name =" NewAccount2" ;;
acct.AccountNumber =" 123457" ;;

HttpClient client = new HttpClient();


var body = JsonConvert.SerializeObject(acct);

var req =(System.Net.HttpWebRequest)System.Net.WebRequest.Create(restCallURL);
req.Headers.Add(" authorization"," Bearer" + authToken);
req.ContentType =" application / json" ;;
req.Method =" POST" ;;

byte [] data = System.Text.Encoding.ASCII.GetBytes(body);
req.ContentLength = body.Length;
var os = req.GetRequestStream();
os.Write(data,0,data.Length);
os.Close();

WebResponse resp;

//试试
// {
resp = req.GetResponse();

谢谢


基思。




基思

解决方案

那你的问题是什么?


替换上述代码的步骤非常简单。

 //如果可能,只应创建一次
var client = new HttpClient();

var content = new StringContent(body);
content.Headers.Add(" Authorization"," Bearer" + authToken);
content.Headers.Add("Content-Type","application / json");
var response = client.PostAsync(url,content);


Hello All,

I would like to have this code refactored to use the HttpClient objects to do a web api post call.

  public class SalesforceAccount
    {


        public string Name { get; set; } 
        public string AccountNumber { get; set; }

    }

var acct = new SalesforceAccount();
                acct.Name = "NewAccount2";
                acct.AccountNumber = "123457";

                HttpClient client = new HttpClient();


                var body = JsonConvert.SerializeObject(acct);

                var req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(restCallURL);
                req.Headers.Add("authorization", "Bearer " + authToken);
                req.ContentType = "application/json";
                req.Method = "POST";

                byte[] data = System.Text.Encoding.ASCII.GetBytes(body);
                req.ContentLength = body.Length;
                var os = req.GetRequestStream();
                os.Write(data, 0, data.Length);
                os.Close();

                WebResponse resp;

              //  try
               // {
                    resp = req.GetResponse();

Thanks

Keith.


keith

解决方案

So what is your question?

The steps to replace the above code is straightforward.

//Should only create this once if possible
var client = new HttpClient();

var content = new StringContent(body);
content.Headers.Add("Authorization", "Bearer " + authToken);
content.Headers.Add("Content-Type", "application/json");
var response = client.PostAsync(url, content);


这篇关于HttpClient API Post Refactor Code的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆