Showdan.Net
c# client for the shodan api
RequestHandler.cs
1 using Newtonsoft.Json;
3 using System;
4 using System.Collections.Generic;
5 using System.Linq;
6 using System.Net.Http;
7 using System.Threading.Tasks;
8 
9 namespace Shodan.Net
10 {
15  {
16  private HttpClient client { get; set; }
17 
18  public async Task<T> MakeRequestAsync<T>(Uri url, HttpContent content = null, RequestType requstType = RequestType.GET)
19  where T : class
20  {
21  if(requstType != RequestType.GET && content == null)
22  {
23  throw new ShodanException($"Request type {requstType} requires content");
24  }
25  if(requstType == RequestType.DELETE || requstType == RequestType.PUT)
26  {
27  throw new NotImplementedException("Put and Delete requests have not been implemented properly");
28  }
29  HttpResponseMessage connection = null;
30  if(requstType == RequestType.GET)
31  {
32  connection = await client.GetAsync(url);
33  }
34  else if(requstType == RequestType.POST)
35  {
36  connection = await client.PostAsync(url, content);
37  }
38 
39  //todo error handle based on user input
40  connection.EnsureSuccessStatusCode();
41 
42  //var statusCode = (int)connection.StatusCode;
43  //if(statusCode != 200 && statusCode != 201 && statusCode == 202)
44  //{
45  // System.Diagnostics.Trace.TraceError("Error calling shodan API, Status code is not 200" + JsonConvert.SerializeObject(connection.s))
46  // //todo error handle
47  // return null;
48  //}
49  var readResult = await connection.Content.ReadAsStringAsync();
50  if(typeof(T) == typeof(string))
51  {
52  return readResult as T;
53  }
54  return JsonConvert.DeserializeObject<T>(readResult);
55  }
56 
57  #region IDisposable Support
58 
59  private bool disposedValue = false; // To detect redundant calls
60 
61  protected virtual void Dispose(bool disposing)
62  {
63  if(!disposedValue)
64  {
65  if(disposing)
66  {
67  client.Dispose();
68  }
69 
70  disposedValue = true;
71  }
72  }
73 
74  // This code added to correctly implement the disposable pattern.
75  public void Dispose()
76  {
77  // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
78  Dispose(true);
79  // TODO: uncomment the following line if the finalizer is overridden above.
80  // GC.SuppressFinalize(this);
81  }
82 
83  #endregion IDisposable Support
84  }
85 }
sane wrapper of http, and simple abstraction layer for unit testing
sane wrapper of http, and simple abstraction layer for unit testing