从代码后端进行API POST

3

我想通过API调用发布一个对象。 我正在使用以下代码在我的codebehind中获取数据

 HttpClient client = new HttpClient();

 client.BaseAddress = new Uri(ConfigurationManager.AppSettings["JUri"]);
 client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));


 HttpResponseMessage response = client.GetAsync("api/receipt/" + jID).Result;
 if (response.IsSuccessStatusCode)
 {}

我想知道是否有与此相当的POST代码。

为什么不为Amount和MailID定义一个模型? - cuongle
有太多的参数,而模型作为参数并不起作用。因此我将其作为单独的字符串传递。 - NewBie
3个回答

3

使用表单进行POST:

HttpClient client = new HttpClient();
client.BaseAddress = new Uri(ConfigurationManager.AppSettings["JUri"]);

var postData = new List<KeyValuePair<string, string>>();

postData.Add(new KeyValuePair<string, string>("Key1", "Value1"));
postData.Add(new KeyValuePair<string, string>("Key2 ", "Value2"));

HttpContent content = new FormUrlEncodedContent(postData);
var response = client.PostAsync("api/receipt/" + jID, content)
if (response.IsSuccessStatusCode)
{}

使用JSON进行POST提交,假设你拥有Dto类:

var client = new HttpClient();
var dto = new Dto {Pro1 = "abc"};

var reponse = client.PostAsJsonAsync("api/receipt/" + jID, dto).Result;

if (reponse.IsSuccessStatusCode)
{}

对于使用JSON的POST请求,我需要将postData设置为键值对吗? - NewBie
@NewBie:不,只需将您的对象传递到方法中即可。 - cuongle
我尝试了你的代码,它帮助我调用了我的POST方法,但是我的参数没有被分配给POST方法的参数。 - NewBie
哦,我的错了...你的代码完美地运行了。是我字符串操作有问题。非常感谢你的帮助。 - NewBie

1
您最好的选择是使用第三方库,比如RestSharp。使用RestSharp向您的API发送请求的简单方法如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Threading;
using RestSharp;
using System.Text.RegularExpressions;

namespace ConsoleApplication2
{
    public class SimpleConnector
    {
        private CookieContainer _cookieJar = new CookieContainer();
        private RestClient client = new RestClient();
        public string TwitterAuthenticate(string user, string pass)
        {
            client.CookieContainer = _cookieJar;
            //RestClient client = new RestClient("https://twitter.com");
            IRestRequest request = new RestRequest("https://twitter.com/", Method.GET);
            client.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:18.0) Gecko/20100101 Firefox/18.0";
            client.AddDefaultHeader("Accept", "*/*");
            //request.AddParameter("name", "value"); // adds to POST or URL querystring based on Method
            //request.AddUrlSegment("id", "123"); // replaces matching token in request.Resource

            // easily add HTTP Headers
            //request.AddHeader("header", "value");

            // add files to upload (works with compatible verbs)

            // execute the request
            IRestResponse response = client.Execute(request);
            var content = response.Content;
            Match m = Regex.Match(content, @"name=""authenticity_token""\s*value=""(.*?)"">");
            string authenticity_token = m.Groups[1].Value;
            request = new RestRequest("https://twitter.com/sessions", Method.POST);
            request.AddParameter("session[username_or_email]", user);
            request.AddParameter("session[password]", pass);
            request.AddParameter("return_to_ssl", "true");
            request.AddParameter("scribe_log", "");
            request.AddParameter("redirect_after_login", "/");
            request.AddParameter("authenticity_token", authenticity_token);
            response = client.Execute(request);
            content = response.Content;
            return content;
        }

有没有什么我可以直接使用的东西,而不需要第三方库?一些简单的东西? - NewBie
你可以使用带有HttpWebRequest.Method的HttpWebRequest,例如POST,然后将你要发布的内容写入流并计算其长度,最后将其发送到服务器。 - Dave Miles

1

Yes, you can do this way:

 HttpClient client = new HttpClient();

 client.BaseAddress = new Uri(ConfigurationManager.AppSettings["JUri"]);

根据您的需求,您可以使用以下任一方法:

Task<HttpResponseMessage> response = client.PostAsJsonAsync();

或者

Task<HttpResponseMessage> response = client.PostAsXmlAsync();

或者

Task<HttpResponseMessage> response = client.PostAsync();

希望这有所帮助!

我在哪里可以传递POST数据?我有一个对象,如何将其作为POST数据发送? - NewBie

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接