过程很是不容易,多花了几天用来找问题,做下记录共享给有需要的人。这是第一篇连接的后续篇。
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; }
}
}
}