How do I make a case request from the Pacer.gov API?

大兔子大兔子 提交于 2019-12-04 17:07:34

There's one major problem with your code. You're only carrying one of the three cookies that checp-pacer-passwd.pl returns. You need to preserve all three. The following code is a possible implementation of this, with some notes afterwards.

public class PacerClient
{
    private CookieContainer m_Cookies = new CookieContainer();
    public string Username { get; set; }
    public string Password { get; set; }
    public PacerClient(string username, string password)
    {
        this.Username = username;
        this.Password = password;
    }
    public void Connect()
    {
        var client = new RestClient("https://pacer.login.uscourts.gov");
        client.CookieContainer = this.m_Cookies;
        RestRequest request = new RestRequest("/cgi-bin/check-pacer-passwd.pl", Method.POST);
        request.AddParameter("loginid", this.Username);
        request.AddParameter("passwd", this.Password);

        IRestResponse response = client.Execute(request);

        if (response.Cookies.Count < 1)
        {
            throw new WebException("No cookies returned.");
        }
    }
    public XmlDocument SearchParty(string partyName)
    {
        string requestUri = $"/dquery?download=1&dl_fmt=xml&party={partyName}";

        var client = new RestClient("https://pcl.uscourts.gov");
        client.CookieContainer = this.m_Cookies;

        var request = new RestRequest(requestUri);

        IRestResponse response = client.Execute(request);

        if (!String.IsNullOrEmpty(response.Content))
        {
            XmlDocument result = new XmlDocument();
            result.LoadXml(response.Content);
            return result;
        }
        else return null;
    }
}

It's easiest to just keep a hold of the CookieContainer throughout the entire time you're working with Pacer. I wrapped the functionality into a class, just to make it a little easier to package up with this answer, but you can implement it however you want. I didn't put in any real error checking, so you probably want to check that response.ResponseUri is actually the search page and not the logon page, and that the content is actually well-formed XML.

I've tested this using my own Pacer account, like so:

PacerClient client = new PacerClient(Username, Password);
client.Connect();
var document = client.SearchParty("Moncrief");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!