Skip to content

Instantly share code, notes, and snippets.

@ZhenDeng
Last active June 27, 2022 03:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ZhenDeng/7f05b63c81c81a0a43e3e2850b5e1452 to your computer and use it in GitHub Desktop.
Save ZhenDeng/7f05b63c81c81a0a43e3e2850b5e1452 to your computer and use it in GitHub Desktop.
var productSearchList = ServiceHubJsonExtractor.GetJsonResult<GetProductSearchList>(url, WebMethods.GET, inputModel, null, GetToken());
public enum WebMethods
{
GET,
POST
}
public static T GetJsonResult<T>(string baseUrl, WebMethods method, dynamic queryParameters = null, dynamic bodyContent = null, dynamic token = null) where T : new()
{
string url = string.Empty;
if (queryParameters != null)
{
url = BuildUrl(baseUrl, queryParameters);
}
else
{
url = baseUrl;
}
var request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Method = method.ToString();
request.ContentType = "application/json";
request.Accept = "application/json";
if (token != null) {
request.Headers.Add("Authorization", $"{token.Token_Type} {token.Access_Token}");
}else{
//use user name and password
var credentials = Convert.ToBase64String(Encoding.Default.GetBytes(UserName + ":" + Password));
request.Headers.Add("Authorization", "Basic " + credentials);
}
var settings = new JsonSerializerSettings
{
PreserveReferencesHandling = PreserveReferencesHandling.Objects,
Converters = { new JsonExtractor.StringOrArrayConverter() },
Error = (sender, args) =>
{
if (System.Diagnostics.Debugger.IsAttached)
{
System.Diagnostics.Debug.Write(args.CurrentObject.ToString());
System.Diagnostics.Debugger.Break();
}
}
};
try
{
if (bodyContent != null)
{
string contentString = string.Empty;
if (bodyContent is String)
{
contentString = bodyContent;
}
else
{
contentString = JsonConvert.SerializeObject(bodyContent);
}
using (var writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(contentString);
}
}else{
request.ContentLength = 0;
}
var response = request.GetResponse();
using (var reader = new StreamReader(response.GetResponseStream()))
{
var responseContent = reader.ReadToEnd();
var result = new T();
try
{
if (!string.IsNullOrWhiteSpace(responseContent))
result = JsonConvert.DeserializeObject<T>(responseContent, settings);
}
catch (Exception ex)
{
throw ex;
}
return result;
}
}
catch (WebException webException)
{
throw webException;
}
}
private static string BuildUrl(string baseUrl, dynamic queryParameters)
{
string url = string.Empty, parameterList = string.Empty;
if (queryParameters != null)
{
try
{
// the parameters could be dictionary or list
Type type = queryParameters.GetType();
if (type.Name == "Dictionary`2" || type.Name == "List`1") // dictionary/list
{
foreach (KeyValuePair<string, string> param in queryParameters)
{
if (parameterList.Length > 0) parameterList += "&";
parameterList += string.Format("{0}={1}", param.Key, param.Value);
}
}
else // class with properties
{
foreach (PropertyInfo propertyInfo in type.GetProperties())
{
if (propertyInfo.CanRead)
{
if (parameterList.Length > 0) parameterList += "&";
parameterList += string.Format("{0}={1}", propertyInfo.Name, propertyInfo.GetValue(queryParameters, null));
}
}
}
}
catch (JsonException jex)
{
throw jex;
}
catch (Exception ex)
{
throw ex;
}
}
if (!string.IsNullOrWhiteSpace(parameterList))
{
url = string.Format("{0}?{1}", baseUrl, parameterList);
}
else
{
url = baseUrl;
}
return url;
}
private class StringOrArrayConverter : JsonConverter
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
switch (reader.TokenType)
{
case JsonToken.String:
return reader.Value;
case JsonToken.Integer:
return reader.Value.ToString();
case JsonToken.Null:
return string.Empty;
}
throw new JsonReaderException("Expected string or null or empty array.");
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
serializer.Serialize(writer, value);
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(string);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment