Skip to content

Instantly share code, notes, and snippets.

@ZhenDeng ZhenDeng/call Restful api
Last active Jan 20, 2019

Embed
What would you like to do?
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}");
}
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);
}
}
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
You can’t perform that action at this time.