c#中restsharp 连接Drupal Rest_Server

过程很是不容易,多花了几天用来找问题,做下记录共享给有需要的人。这是第一篇连接的后续篇。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RestSharp;
using RestSharp.Authenticators;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;


namespace test_rest
{
    class Program
    {
        public class login_user2
        {

            public string sessid { get; set; }
            public string session_name { get; set; }
            public string token { get; set; }
            public string session_token { get; set; }
            public user_data user { get; set; }
            public class user_data
            {

                public string uid { get; set; }
                public string name { get; set; }
                public string username { get; set; }
                public string password { get; set; }

            }
        }
        private const string base_url2 = "http://yourdomain/services/";

        static void Main(string[] args)
        {
            try
            {
                RestClient client = new RestClient(base_url2);
                var request = new RestRequest("user/login.json", Method.POST);
                request.AddHeader("Content-Type", "application/x-www-form-urlencoded");                
                client.Authenticator = new SimpleAuthenticator("username","username","password","password");
                var restResponse = client.Execute(request);
                var content = restResponse.Content;
                if (restResponse.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    login_user2 loginuser = JsonConvert.DeserializeObject<login_user2>(content.ToString());
                    request =new  RestRequest("node", Method.POST);
                    request.AddParameter(loginuser.session_name,loginuser.sessid,ParameterType.Cookie);
                    request.AddHeader("cache-control", "no-cache");
                    request.AddHeader("x-csrf-token", loginuser.token);
                    request.AddHeader("content-type", "application/x-www-form-urlencoded");
                    request.AddHeader("User-Agent", "My Scanner");                   
                    request.AddParameter("application/x-www-form-urlencoded", "type=article&title=he%20test%20is%20", ParameterType.RequestBody);
                    IRestResponse response = client.Execute(request);
                    Console.WriteLine(response.StatusCode.ToString());                 
                    
                }             

            }
            catch (Exception ex) { throw ex; }

        }
    
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值