forked from loafle/openapi-generator-original
udpate csharp client with restsharp
This commit is contained in:
parent
5c057e1306
commit
8818c209df
@ -80,7 +80,7 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig
|
||||
typeMapping.put("double", "double?");
|
||||
typeMapping.put("number", "double?");
|
||||
typeMapping.put("Date", "DateTime");
|
||||
typeMapping.put("file", "byte[]");
|
||||
typeMapping.put("file", "string"); // path to file
|
||||
typeMapping.put("array", "List");
|
||||
typeMapping.put("map", "Dictionary");
|
||||
|
||||
|
@ -10,27 +10,29 @@ namespace {{package}} {
|
||||
{{#operations}}
|
||||
public class {{classname}} {
|
||||
string basePath;
|
||||
private readonly ApiInvoker apiInvoker = ApiInvoker.GetInstance();
|
||||
protected RestClient _client;
|
||||
protected RestClient restClient;
|
||||
|
||||
public {{classname}}(String basePath = "{{basePath}}")
|
||||
{
|
||||
this.basePath = basePath;
|
||||
_client = new RestClient(basePath);
|
||||
this.restClient = new RestClient(basePath);
|
||||
}
|
||||
|
||||
public ApiInvoker getInvoker() {
|
||||
return apiInvoker;
|
||||
}
|
||||
|
||||
// Sets the endpoint base url for the services being accessed
|
||||
public void setBasePath(string basePath) {
|
||||
/// <summary>
|
||||
/// Sets the endpoint base url for the services being accessed
|
||||
/// </summary>
|
||||
/// <param name="basePath"> Base URL
|
||||
/// <returns></returns>
|
||||
public void SetBasePath(string basePath) {
|
||||
this.basePath = basePath;
|
||||
}
|
||||
|
||||
// Gets the endpoint base url for the services being accessed
|
||||
public String getBasePath() {
|
||||
return basePath;
|
||||
/// <summary>
|
||||
/// Gets the endpoint base url for the services being accessed
|
||||
/// <returns>Base URL</returns>
|
||||
/// </summary>
|
||||
public String GetBasePath() {
|
||||
return this.basePath;
|
||||
}
|
||||
|
||||
{{#operation}}
|
||||
@ -39,7 +41,7 @@ namespace {{package}} {
|
||||
/// {{summary}} {{notes}}
|
||||
/// </summary>
|
||||
{{#allParams}}/// <param name="{{paramName}}">{{description}}</param>
|
||||
{{#hasMore}} {{/hasMore}}{{/allParams}}
|
||||
{{/allParams}}
|
||||
/// <returns></returns>
|
||||
public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) {
|
||||
|
||||
@ -52,20 +54,23 @@ namespace {{package}} {
|
||||
|
||||
// path (url segment) parameters
|
||||
_request.AddUrlSegment("format", "json"); // set format to json by default
|
||||
{{#pathParams}}_request.AddUrlSegment("{{baseName}}", apiInvoker.ParameterToString({{{paramName}}}));{{/pathParams}}
|
||||
{{#pathParams}}_request.AddUrlSegment("{{baseName}}", ApiInvoker.ParameterToString({{{paramName}}}));{{/pathParams}}
|
||||
// query parameters, if any
|
||||
{{#queryParams}} if ({{paramName}} != null) _request.AddParameter("{{baseName}}", {{paramName}});{{/queryParams}}
|
||||
// header parameters, if any
|
||||
{{#headerParams}} if ({{paramName}} != null) _request.AddHeader("{{baseName}}", {{paramName}});{{/headerParams}}
|
||||
// form parameters, if any
|
||||
{{#formParams}}if ({{paramName}} != null) {{#isFile}}_request.AddParameter("{{baseName}}", {{paramName}});{{/isFile}}{{^isFile}}_request.AddFile("{{baseName}}", {{paramName}});{{/isFile}}
|
||||
{{#formParams}}if ({{paramName}} != null) {{#isFile}}_request.AddFile("{{baseName}}", {{paramName}});{{/isFile}}{{^isFile}}_request.AddParameter("{{baseName}}", {{paramName}});{{/isFile}}
|
||||
{{/formParams}}
|
||||
{{#bodyParam}}
|
||||
_request.AddParameter("application/json", ApiInvoker.Serialize({{paramName}}), ParameterType.RequestBody);
|
||||
{{/bodyParam}}
|
||||
|
||||
try {
|
||||
{{#returnType}}IRestResponse response = _client.Execute(_request);
|
||||
return ({{{returnType}}}) ApiInvoker.deserialize(response.Content, typeof({{{returnType}}}));
|
||||
{{#returnType}}IRestResponse response = restClient.Execute(_request);
|
||||
return ({{{returnType}}}) ApiInvoker.Deserialize(response.Content, typeof({{{returnType}}}));
|
||||
//return ((object)response) as {{{returnType}}};{{/returnType}}
|
||||
{{^returnType}}_client.Execute(_request);
|
||||
{{^returnType}}restClient.Execute(_request);
|
||||
return;{{/returnType}}
|
||||
} catch (Exception ex) {
|
||||
if(ex != null) {
|
||||
|
@ -1,19 +1,14 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using Newtonsoft.Json;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace {{invokerPackage}} {
|
||||
namespace {{invokerPackage}} {
|
||||
public class ApiInvoker {
|
||||
private static readonly ApiInvoker _instance = new ApiInvoker();
|
||||
private Dictionary<String, String> defaultHeaderMap = new Dictionary<String, String>();
|
||||
|
||||
public static ApiInvoker GetInstance() {
|
||||
return _instance;
|
||||
}
|
||||
private static Dictionary<String, String> defaultHeaderMap = new Dictionary<String, String>();
|
||||
|
||||
/// <summary>
|
||||
/// Add default header
|
||||
@ -21,16 +16,24 @@
|
||||
/// <param name="key"> Header field name
|
||||
/// <param name="value"> Header field value
|
||||
/// <returns></returns>
|
||||
public void addDefaultHeader(string key, string value) {
|
||||
public static void AddDefaultHeader(string key, string value) {
|
||||
defaultHeaderMap.Add(key, value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get default header
|
||||
/// </summary>
|
||||
/// <returns>Dictionary of default header</returns>
|
||||
public static Dictionary<String, String> GetDefaultHeader() {
|
||||
return defaultHeaderMap;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// escape string (url-encoded)
|
||||
/// </summary>
|
||||
/// <param name="str"> String to be escaped
|
||||
/// <returns>Escaped string</returns>
|
||||
public string escapeString(string str) {
|
||||
public static string EscapeString(string str) {
|
||||
return str;
|
||||
}
|
||||
|
||||
@ -39,7 +42,7 @@
|
||||
/// </summary>
|
||||
/// <param name="obj"> The parameter (header, path, query, form)
|
||||
/// <returns>Formatted string</returns>
|
||||
public string ParameterToString(object obj)
|
||||
public static string ParameterToString(object obj)
|
||||
{
|
||||
return (obj is DateTime) ? ((DateTime)obj).ToString ("u") : Convert.ToString (obj);
|
||||
}
|
||||
@ -50,7 +53,7 @@
|
||||
/// <param name="json"> JSON string
|
||||
/// <param name="type"> Object type
|
||||
/// <returns>Object representation of the JSON string</returns>
|
||||
public static object deserialize(string json, Type type) {
|
||||
public static object Deserialize(string json, Type type) {
|
||||
try
|
||||
{
|
||||
return JsonConvert.DeserializeObject(json, type);
|
||||
@ -58,10 +61,14 @@
|
||||
catch (IOException e) {
|
||||
throw new ApiException(500, e.Message);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static string serialize(object obj) {
|
||||
/// <summary>
|
||||
/// Serialize an object into JSON string
|
||||
/// </summary>
|
||||
/// <param name="obj"> Object
|
||||
/// <returns>JSON string</returns>
|
||||
public static string Serialize(object obj) {
|
||||
try
|
||||
{
|
||||
return obj != null ? JsonConvert.SerializeObject(obj) : null;
|
||||
@ -70,166 +77,5 @@
|
||||
throw new ApiException(500, e.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public string invokeAPI(string host, string path, string method, Dictionary<String, String> queryParams, object body, Dictionary<String, String> headerParams, Dictionary<String, object> formParams)
|
||||
{
|
||||
return invokeAPIInternal(host, path, method, false, queryParams, body, headerParams, formParams) as string;
|
||||
}
|
||||
|
||||
public byte[] invokeBinaryAPI(string host, string path, string method, Dictionary<String, String> queryParams, object body, Dictionary<String, String> headerParams, Dictionary<String, object> formParams)
|
||||
{
|
||||
return invokeAPIInternal(host, path, method, true, queryParams, body, headerParams, formParams) as byte[];
|
||||
}
|
||||
|
||||
private object invokeAPIInternal(string host, string path, string method, bool binaryResponse, Dictionary<String, String> queryParams, object body, Dictionary<String, String> headerParams, Dictionary<String, object> formParams) {
|
||||
var b = new StringBuilder();
|
||||
|
||||
foreach (var queryParamItem in queryParams)
|
||||
{
|
||||
var value = queryParamItem.Value;
|
||||
if (value == null) continue;
|
||||
b.Append(b.ToString().Length == 0 ? "?" : "&");
|
||||
b.Append(escapeString(queryParamItem.Key)).Append("=").Append(escapeString(value));
|
||||
}
|
||||
|
||||
var querystring = b.ToString();
|
||||
|
||||
host = host.EndsWith("/") ? host.Substring(0, host.Length - 1) : host;
|
||||
|
||||
var client = WebRequest.Create(host + path + querystring);
|
||||
client.Method = method;
|
||||
|
||||
byte[] formData = null;
|
||||
if (formParams.Count > 0)
|
||||
{
|
||||
string formDataBoundary = String.Format("----------{0:N}", Guid.NewGuid());
|
||||
client.ContentType = "multipart/form-data; boundary=" + formDataBoundary;
|
||||
formData = GetMultipartFormData(formParams, formDataBoundary);
|
||||
client.ContentLength = formData.Length;
|
||||
}
|
||||
else
|
||||
{
|
||||
client.ContentType = "application/json";
|
||||
}
|
||||
|
||||
foreach (var headerParamsItem in headerParams)
|
||||
{
|
||||
client.Headers.Add(headerParamsItem.Key, headerParamsItem.Value);
|
||||
}
|
||||
foreach (var defaultHeaderMapItem in defaultHeaderMap.Where(defaultHeaderMapItem => !headerParams.ContainsKey(defaultHeaderMapItem.Key)))
|
||||
{
|
||||
client.Headers.Add(defaultHeaderMapItem.Key, defaultHeaderMapItem.Value);
|
||||
}
|
||||
|
||||
switch (method)
|
||||
{
|
||||
case "GET":
|
||||
break;
|
||||
case "POST":
|
||||
case "PATCH":
|
||||
case "PUT":
|
||||
case "DELETE":
|
||||
using (Stream requestStream = client.GetRequestStream())
|
||||
{
|
||||
if (formData != null)
|
||||
{
|
||||
requestStream.Write(formData, 0, formData.Length);
|
||||
}
|
||||
|
||||
var swRequestWriter = new StreamWriter(requestStream);
|
||||
swRequestWriter.Write(serialize(body));
|
||||
swRequestWriter.Close();
|
||||
}
|
||||
break;
|
||||
default:
|
||||
throw new ApiException(500, "unknown method type " + method);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var webResponse = (HttpWebResponse)client.GetResponse();
|
||||
if (webResponse.StatusCode != HttpStatusCode.OK)
|
||||
{
|
||||
webResponse.Close();
|
||||
throw new ApiException((int)webResponse.StatusCode, webResponse.StatusDescription);
|
||||
}
|
||||
|
||||
if (binaryResponse)
|
||||
{
|
||||
using (var memoryStream = new MemoryStream())
|
||||
{
|
||||
webResponse.GetResponseStream().CopyTo(memoryStream);
|
||||
return memoryStream.ToArray();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
using (var responseReader = new StreamReader(webResponse.GetResponseStream()))
|
||||
{
|
||||
var responseData = responseReader.ReadToEnd();
|
||||
return responseData;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch(WebException ex)
|
||||
{
|
||||
var response = ex.Response as HttpWebResponse;
|
||||
int statusCode = 0;
|
||||
if (response != null)
|
||||
{
|
||||
statusCode = (int)response.StatusCode;
|
||||
response.Close();
|
||||
}
|
||||
throw new ApiException(statusCode, ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] GetMultipartFormData(Dictionary<string, object> postParameters, string boundary)
|
||||
{
|
||||
Stream formDataStream = new System.IO.MemoryStream();
|
||||
bool needsCLRF = false;
|
||||
|
||||
foreach (var param in postParameters)
|
||||
{
|
||||
// Thanks to feedback from commenters, add a CRLF to allow multiple parameters to be added.
|
||||
// Skip it on the first parameter, add it to subsequent parameters.
|
||||
if (needsCLRF)
|
||||
formDataStream.Write(Encoding.UTF8.GetBytes("\r\n"), 0, Encoding.UTF8.GetByteCount("\r\n"));
|
||||
|
||||
needsCLRF = true;
|
||||
|
||||
if (param.Value is byte[])
|
||||
{
|
||||
string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n",
|
||||
boundary,
|
||||
param.Key,
|
||||
"application/octet-stream");
|
||||
formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData));
|
||||
|
||||
// Write the file data directly to the Stream, rather than serializing it to a string.
|
||||
formDataStream.Write((param.Value as byte[]), 0, (param.Value as byte[]).Length);
|
||||
}
|
||||
else
|
||||
{
|
||||
string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}",
|
||||
boundary,
|
||||
param.Key,
|
||||
param.Value);
|
||||
formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData));
|
||||
}
|
||||
}
|
||||
|
||||
// Add the end of the request. Start with a newline
|
||||
string footer = "\r\n--" + boundary + "--\r\n";
|
||||
formDataStream.Write(Encoding.UTF8.GetBytes(footer), 0, Encoding.UTF8.GetByteCount(footer));
|
||||
|
||||
// Dump the Stream into a byte[]
|
||||
formDataStream.Position = 0;
|
||||
byte[] formData = new byte[formDataStream.Length];
|
||||
formDataStream.Read(formData, 0, formData.Length);
|
||||
formDataStream.Close();
|
||||
|
||||
return formData;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -2,19 +2,19 @@ using System;
|
||||
using System.Text;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
{{#models}}
|
||||
{{#model}}
|
||||
namespace {{package}} {
|
||||
[DataContract]
|
||||
public class {{classname}} {
|
||||
{{#vars}}
|
||||
|
||||
{{#description}}/* {{{description}}} */
|
||||
{{/description}}
|
||||
{{#description}}/* {{{description}}} */{{/description}}
|
||||
[DataMember(Name="{{baseName}}", EmitDefaultValue=false)]
|
||||
public {{{datatype}}} {{name}} { get; set; }
|
||||
|
||||
{{/vars}}
|
||||
|
||||
public override string ToString() {
|
||||
var sb = new StringBuilder();
|
||||
sb.Append("class {{classname}} {\n");
|
||||
|
@ -8,27 +8,29 @@ namespace io.swagger.Api {
|
||||
|
||||
public class PetApi {
|
||||
string basePath;
|
||||
private readonly ApiInvoker apiInvoker = ApiInvoker.GetInstance();
|
||||
protected RestClient _client;
|
||||
protected RestClient restClient;
|
||||
|
||||
public PetApi(String basePath = "http://petstore.swagger.io/v2")
|
||||
{
|
||||
this.basePath = basePath;
|
||||
_client = new RestClient(basePath);
|
||||
this.restClient = new RestClient(basePath);
|
||||
}
|
||||
|
||||
public ApiInvoker getInvoker() {
|
||||
return apiInvoker;
|
||||
}
|
||||
|
||||
// Sets the endpoint base url for the services being accessed
|
||||
public void setBasePath(string basePath) {
|
||||
/// <summary>
|
||||
/// Sets the endpoint base url for the services being accessed
|
||||
/// </summary>
|
||||
/// <param name="basePath"> Base URL
|
||||
/// <returns></returns>
|
||||
public void SetBasePath(string basePath) {
|
||||
this.basePath = basePath;
|
||||
}
|
||||
|
||||
// Gets the endpoint base url for the services being accessed
|
||||
public String getBasePath() {
|
||||
return basePath;
|
||||
/// <summary>
|
||||
/// Gets the endpoint base url for the services being accessed
|
||||
/// <returns>Base URL</returns>
|
||||
/// </summary>
|
||||
public String GetBasePath() {
|
||||
return this.basePath;
|
||||
}
|
||||
|
||||
|
||||
@ -57,9 +59,12 @@ namespace io.swagger.Api {
|
||||
// form parameters, if any
|
||||
|
||||
|
||||
_request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody);
|
||||
|
||||
|
||||
try {
|
||||
|
||||
_client.Execute(_request);
|
||||
restClient.Execute(_request);
|
||||
return;
|
||||
} catch (Exception ex) {
|
||||
if(ex != null) {
|
||||
@ -96,9 +101,12 @@ namespace io.swagger.Api {
|
||||
// form parameters, if any
|
||||
|
||||
|
||||
_request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody);
|
||||
|
||||
|
||||
try {
|
||||
|
||||
_client.Execute(_request);
|
||||
restClient.Execute(_request);
|
||||
return;
|
||||
} catch (Exception ex) {
|
||||
if(ex != null) {
|
||||
@ -135,9 +143,10 @@ namespace io.swagger.Api {
|
||||
// form parameters, if any
|
||||
|
||||
|
||||
|
||||
try {
|
||||
IRestResponse response = _client.Execute(_request);
|
||||
return (List<Pet>) ApiInvoker.deserialize(response.Content, typeof(List<Pet>));
|
||||
IRestResponse response = restClient.Execute(_request);
|
||||
return (List<Pet>) ApiInvoker.Deserialize(response.Content, typeof(List<Pet>));
|
||||
//return ((object)response) as List<Pet>;
|
||||
|
||||
} catch (Exception ex) {
|
||||
@ -175,9 +184,10 @@ namespace io.swagger.Api {
|
||||
// form parameters, if any
|
||||
|
||||
|
||||
|
||||
try {
|
||||
IRestResponse response = _client.Execute(_request);
|
||||
return (List<Pet>) ApiInvoker.deserialize(response.Content, typeof(List<Pet>));
|
||||
IRestResponse response = restClient.Execute(_request);
|
||||
return (List<Pet>) ApiInvoker.Deserialize(response.Content, typeof(List<Pet>));
|
||||
//return ((object)response) as List<Pet>;
|
||||
|
||||
} catch (Exception ex) {
|
||||
@ -207,7 +217,7 @@ namespace io.swagger.Api {
|
||||
|
||||
// path (url segment) parameters
|
||||
_request.AddUrlSegment("format", "json"); // set format to json by default
|
||||
_request.AddUrlSegment("petId", apiInvoker.ParameterToString(PetId));
|
||||
_request.AddUrlSegment("petId", ApiInvoker.ParameterToString(PetId));
|
||||
// query parameters, if any
|
||||
|
||||
// header parameters, if any
|
||||
@ -215,9 +225,10 @@ namespace io.swagger.Api {
|
||||
// form parameters, if any
|
||||
|
||||
|
||||
|
||||
try {
|
||||
IRestResponse response = _client.Execute(_request);
|
||||
return (Pet) ApiInvoker.deserialize(response.Content, typeof(Pet));
|
||||
IRestResponse response = restClient.Execute(_request);
|
||||
return (Pet) ApiInvoker.Deserialize(response.Content, typeof(Pet));
|
||||
//return ((object)response) as Pet;
|
||||
|
||||
} catch (Exception ex) {
|
||||
@ -249,19 +260,20 @@ namespace io.swagger.Api {
|
||||
|
||||
// path (url segment) parameters
|
||||
_request.AddUrlSegment("format", "json"); // set format to json by default
|
||||
_request.AddUrlSegment("petId", apiInvoker.ParameterToString(PetId));
|
||||
_request.AddUrlSegment("petId", ApiInvoker.ParameterToString(PetId));
|
||||
// query parameters, if any
|
||||
|
||||
// header parameters, if any
|
||||
|
||||
// form parameters, if any
|
||||
if (Name != null) _request.AddFile("name", Name);
|
||||
if (Status != null) _request.AddFile("status", Status);
|
||||
if (Name != null) _request.AddParameter("name", Name);
|
||||
if (Status != null) _request.AddParameter("status", Status);
|
||||
|
||||
|
||||
|
||||
try {
|
||||
|
||||
_client.Execute(_request);
|
||||
restClient.Execute(_request);
|
||||
return;
|
||||
} catch (Exception ex) {
|
||||
if(ex != null) {
|
||||
@ -291,7 +303,7 @@ namespace io.swagger.Api {
|
||||
|
||||
// path (url segment) parameters
|
||||
_request.AddUrlSegment("format", "json"); // set format to json by default
|
||||
_request.AddUrlSegment("petId", apiInvoker.ParameterToString(PetId));
|
||||
_request.AddUrlSegment("petId", ApiInvoker.ParameterToString(PetId));
|
||||
// query parameters, if any
|
||||
|
||||
// header parameters, if any
|
||||
@ -299,9 +311,10 @@ namespace io.swagger.Api {
|
||||
// form parameters, if any
|
||||
|
||||
|
||||
|
||||
try {
|
||||
|
||||
_client.Execute(_request);
|
||||
restClient.Execute(_request);
|
||||
return;
|
||||
} catch (Exception ex) {
|
||||
if(ex != null) {
|
||||
@ -332,19 +345,20 @@ namespace io.swagger.Api {
|
||||
|
||||
// path (url segment) parameters
|
||||
_request.AddUrlSegment("format", "json"); // set format to json by default
|
||||
_request.AddUrlSegment("petId", apiInvoker.ParameterToString(PetId));
|
||||
_request.AddUrlSegment("petId", ApiInvoker.ParameterToString(PetId));
|
||||
// query parameters, if any
|
||||
|
||||
// header parameters, if any
|
||||
|
||||
// form parameters, if any
|
||||
if (AdditionalMetadata != null) _request.AddFile("additionalMetadata", AdditionalMetadata);
|
||||
if (File != null) _request.AddParameter("file", File);
|
||||
if (AdditionalMetadata != null) _request.AddParameter("additionalMetadata", AdditionalMetadata);
|
||||
if (File != null) _request.AddFile("file", File);
|
||||
|
||||
|
||||
|
||||
try {
|
||||
|
||||
_client.Execute(_request);
|
||||
restClient.Execute(_request);
|
||||
return;
|
||||
} catch (Exception ex) {
|
||||
if(ex != null) {
|
||||
|
@ -8,27 +8,29 @@ namespace io.swagger.Api {
|
||||
|
||||
public class StoreApi {
|
||||
string basePath;
|
||||
private readonly ApiInvoker apiInvoker = ApiInvoker.GetInstance();
|
||||
protected RestClient _client;
|
||||
protected RestClient restClient;
|
||||
|
||||
public StoreApi(String basePath = "http://petstore.swagger.io/v2")
|
||||
{
|
||||
this.basePath = basePath;
|
||||
_client = new RestClient(basePath);
|
||||
this.restClient = new RestClient(basePath);
|
||||
}
|
||||
|
||||
public ApiInvoker getInvoker() {
|
||||
return apiInvoker;
|
||||
}
|
||||
|
||||
// Sets the endpoint base url for the services being accessed
|
||||
public void setBasePath(string basePath) {
|
||||
/// <summary>
|
||||
/// Sets the endpoint base url for the services being accessed
|
||||
/// </summary>
|
||||
/// <param name="basePath"> Base URL
|
||||
/// <returns></returns>
|
||||
public void SetBasePath(string basePath) {
|
||||
this.basePath = basePath;
|
||||
}
|
||||
|
||||
// Gets the endpoint base url for the services being accessed
|
||||
public String getBasePath() {
|
||||
return basePath;
|
||||
/// <summary>
|
||||
/// Gets the endpoint base url for the services being accessed
|
||||
/// <returns>Base URL</returns>
|
||||
/// </summary>
|
||||
public String GetBasePath() {
|
||||
return this.basePath;
|
||||
}
|
||||
|
||||
|
||||
@ -56,9 +58,10 @@ namespace io.swagger.Api {
|
||||
// form parameters, if any
|
||||
|
||||
|
||||
|
||||
try {
|
||||
IRestResponse response = _client.Execute(_request);
|
||||
return (Dictionary<String, int?>) ApiInvoker.deserialize(response.Content, typeof(Dictionary<String, int?>));
|
||||
IRestResponse response = restClient.Execute(_request);
|
||||
return (Dictionary<String, int?>) ApiInvoker.Deserialize(response.Content, typeof(Dictionary<String, int?>));
|
||||
//return ((object)response) as Dictionary<String, int?>;
|
||||
|
||||
} catch (Exception ex) {
|
||||
@ -96,9 +99,12 @@ namespace io.swagger.Api {
|
||||
// form parameters, if any
|
||||
|
||||
|
||||
_request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody);
|
||||
|
||||
|
||||
try {
|
||||
IRestResponse response = _client.Execute(_request);
|
||||
return (Order) ApiInvoker.deserialize(response.Content, typeof(Order));
|
||||
IRestResponse response = restClient.Execute(_request);
|
||||
return (Order) ApiInvoker.Deserialize(response.Content, typeof(Order));
|
||||
//return ((object)response) as Order;
|
||||
|
||||
} catch (Exception ex) {
|
||||
@ -128,7 +134,7 @@ namespace io.swagger.Api {
|
||||
|
||||
// path (url segment) parameters
|
||||
_request.AddUrlSegment("format", "json"); // set format to json by default
|
||||
_request.AddUrlSegment("orderId", apiInvoker.ParameterToString(OrderId));
|
||||
_request.AddUrlSegment("orderId", ApiInvoker.ParameterToString(OrderId));
|
||||
// query parameters, if any
|
||||
|
||||
// header parameters, if any
|
||||
@ -136,9 +142,10 @@ namespace io.swagger.Api {
|
||||
// form parameters, if any
|
||||
|
||||
|
||||
|
||||
try {
|
||||
IRestResponse response = _client.Execute(_request);
|
||||
return (Order) ApiInvoker.deserialize(response.Content, typeof(Order));
|
||||
IRestResponse response = restClient.Execute(_request);
|
||||
return (Order) ApiInvoker.Deserialize(response.Content, typeof(Order));
|
||||
//return ((object)response) as Order;
|
||||
|
||||
} catch (Exception ex) {
|
||||
@ -168,7 +175,7 @@ namespace io.swagger.Api {
|
||||
|
||||
// path (url segment) parameters
|
||||
_request.AddUrlSegment("format", "json"); // set format to json by default
|
||||
_request.AddUrlSegment("orderId", apiInvoker.ParameterToString(OrderId));
|
||||
_request.AddUrlSegment("orderId", ApiInvoker.ParameterToString(OrderId));
|
||||
// query parameters, if any
|
||||
|
||||
// header parameters, if any
|
||||
@ -176,9 +183,10 @@ namespace io.swagger.Api {
|
||||
// form parameters, if any
|
||||
|
||||
|
||||
|
||||
try {
|
||||
|
||||
_client.Execute(_request);
|
||||
restClient.Execute(_request);
|
||||
return;
|
||||
} catch (Exception ex) {
|
||||
if(ex != null) {
|
||||
|
@ -8,27 +8,29 @@ namespace io.swagger.Api {
|
||||
|
||||
public class UserApi {
|
||||
string basePath;
|
||||
private readonly ApiInvoker apiInvoker = ApiInvoker.GetInstance();
|
||||
protected RestClient _client;
|
||||
protected RestClient restClient;
|
||||
|
||||
public UserApi(String basePath = "http://petstore.swagger.io/v2")
|
||||
{
|
||||
this.basePath = basePath;
|
||||
_client = new RestClient(basePath);
|
||||
this.restClient = new RestClient(basePath);
|
||||
}
|
||||
|
||||
public ApiInvoker getInvoker() {
|
||||
return apiInvoker;
|
||||
}
|
||||
|
||||
// Sets the endpoint base url for the services being accessed
|
||||
public void setBasePath(string basePath) {
|
||||
/// <summary>
|
||||
/// Sets the endpoint base url for the services being accessed
|
||||
/// </summary>
|
||||
/// <param name="basePath"> Base URL
|
||||
/// <returns></returns>
|
||||
public void SetBasePath(string basePath) {
|
||||
this.basePath = basePath;
|
||||
}
|
||||
|
||||
// Gets the endpoint base url for the services being accessed
|
||||
public String getBasePath() {
|
||||
return basePath;
|
||||
/// <summary>
|
||||
/// Gets the endpoint base url for the services being accessed
|
||||
/// <returns>Base URL</returns>
|
||||
/// </summary>
|
||||
public String GetBasePath() {
|
||||
return this.basePath;
|
||||
}
|
||||
|
||||
|
||||
@ -57,9 +59,12 @@ namespace io.swagger.Api {
|
||||
// form parameters, if any
|
||||
|
||||
|
||||
_request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody);
|
||||
|
||||
|
||||
try {
|
||||
|
||||
_client.Execute(_request);
|
||||
restClient.Execute(_request);
|
||||
return;
|
||||
} catch (Exception ex) {
|
||||
if(ex != null) {
|
||||
@ -96,9 +101,12 @@ namespace io.swagger.Api {
|
||||
// form parameters, if any
|
||||
|
||||
|
||||
_request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody);
|
||||
|
||||
|
||||
try {
|
||||
|
||||
_client.Execute(_request);
|
||||
restClient.Execute(_request);
|
||||
return;
|
||||
} catch (Exception ex) {
|
||||
if(ex != null) {
|
||||
@ -135,9 +143,12 @@ namespace io.swagger.Api {
|
||||
// form parameters, if any
|
||||
|
||||
|
||||
_request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody);
|
||||
|
||||
|
||||
try {
|
||||
|
||||
_client.Execute(_request);
|
||||
restClient.Execute(_request);
|
||||
return;
|
||||
} catch (Exception ex) {
|
||||
if(ex != null) {
|
||||
@ -175,9 +186,10 @@ namespace io.swagger.Api {
|
||||
// form parameters, if any
|
||||
|
||||
|
||||
|
||||
try {
|
||||
IRestResponse response = _client.Execute(_request);
|
||||
return (string) ApiInvoker.deserialize(response.Content, typeof(string));
|
||||
IRestResponse response = restClient.Execute(_request);
|
||||
return (string) ApiInvoker.Deserialize(response.Content, typeof(string));
|
||||
//return ((object)response) as string;
|
||||
|
||||
} catch (Exception ex) {
|
||||
@ -214,9 +226,10 @@ namespace io.swagger.Api {
|
||||
// form parameters, if any
|
||||
|
||||
|
||||
|
||||
try {
|
||||
|
||||
_client.Execute(_request);
|
||||
restClient.Execute(_request);
|
||||
return;
|
||||
} catch (Exception ex) {
|
||||
if(ex != null) {
|
||||
@ -245,7 +258,7 @@ namespace io.swagger.Api {
|
||||
|
||||
// path (url segment) parameters
|
||||
_request.AddUrlSegment("format", "json"); // set format to json by default
|
||||
_request.AddUrlSegment("username", apiInvoker.ParameterToString(Username));
|
||||
_request.AddUrlSegment("username", ApiInvoker.ParameterToString(Username));
|
||||
// query parameters, if any
|
||||
|
||||
// header parameters, if any
|
||||
@ -253,9 +266,10 @@ namespace io.swagger.Api {
|
||||
// form parameters, if any
|
||||
|
||||
|
||||
|
||||
try {
|
||||
IRestResponse response = _client.Execute(_request);
|
||||
return (User) ApiInvoker.deserialize(response.Content, typeof(User));
|
||||
IRestResponse response = restClient.Execute(_request);
|
||||
return (User) ApiInvoker.Deserialize(response.Content, typeof(User));
|
||||
//return ((object)response) as User;
|
||||
|
||||
} catch (Exception ex) {
|
||||
@ -286,7 +300,7 @@ namespace io.swagger.Api {
|
||||
|
||||
// path (url segment) parameters
|
||||
_request.AddUrlSegment("format", "json"); // set format to json by default
|
||||
_request.AddUrlSegment("username", apiInvoker.ParameterToString(Username));
|
||||
_request.AddUrlSegment("username", ApiInvoker.ParameterToString(Username));
|
||||
// query parameters, if any
|
||||
|
||||
// header parameters, if any
|
||||
@ -294,9 +308,12 @@ namespace io.swagger.Api {
|
||||
// form parameters, if any
|
||||
|
||||
|
||||
_request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody);
|
||||
|
||||
|
||||
try {
|
||||
|
||||
_client.Execute(_request);
|
||||
restClient.Execute(_request);
|
||||
return;
|
||||
} catch (Exception ex) {
|
||||
if(ex != null) {
|
||||
@ -325,7 +342,7 @@ namespace io.swagger.Api {
|
||||
|
||||
// path (url segment) parameters
|
||||
_request.AddUrlSegment("format", "json"); // set format to json by default
|
||||
_request.AddUrlSegment("username", apiInvoker.ParameterToString(Username));
|
||||
_request.AddUrlSegment("username", ApiInvoker.ParameterToString(Username));
|
||||
// query parameters, if any
|
||||
|
||||
// header parameters, if any
|
||||
@ -333,9 +350,10 @@ namespace io.swagger.Api {
|
||||
// form parameters, if any
|
||||
|
||||
|
||||
|
||||
try {
|
||||
|
||||
_client.Execute(_request);
|
||||
restClient.Execute(_request);
|
||||
return;
|
||||
} catch (Exception ex) {
|
||||
if(ex != null) {
|
||||
|
@ -2,21 +2,22 @@ using System;
|
||||
using System.Text;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
namespace io.swagger.Model {
|
||||
[DataContract]
|
||||
public class Category {
|
||||
|
||||
|
||||
|
||||
[DataMember(Name="id", EmitDefaultValue=false)]
|
||||
public long? Id { get; set; }
|
||||
|
||||
|
||||
|
||||
|
||||
[DataMember(Name="name", EmitDefaultValue=false)]
|
||||
public string Name { get; set; }
|
||||
|
||||
|
||||
|
||||
public override string ToString() {
|
||||
var sb = new StringBuilder();
|
||||
sb.Append("class Category {\n");
|
||||
|
@ -2,42 +2,42 @@ using System;
|
||||
using System.Text;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
namespace io.swagger.Model {
|
||||
[DataContract]
|
||||
public class Order {
|
||||
|
||||
|
||||
|
||||
[DataMember(Name="id", EmitDefaultValue=false)]
|
||||
public long? Id { get; set; }
|
||||
|
||||
|
||||
|
||||
|
||||
[DataMember(Name="petId", EmitDefaultValue=false)]
|
||||
public long? PetId { get; set; }
|
||||
|
||||
|
||||
|
||||
|
||||
[DataMember(Name="quantity", EmitDefaultValue=false)]
|
||||
public int? Quantity { get; set; }
|
||||
|
||||
|
||||
|
||||
|
||||
[DataMember(Name="shipDate", EmitDefaultValue=false)]
|
||||
public DateTime ShipDate { get; set; }
|
||||
|
||||
|
||||
|
||||
/* Order Status */
|
||||
|
||||
[DataMember(Name="status", EmitDefaultValue=false)]
|
||||
public string Status { get; set; }
|
||||
|
||||
|
||||
|
||||
|
||||
[DataMember(Name="complete", EmitDefaultValue=false)]
|
||||
public bool? Complete { get; set; }
|
||||
|
||||
|
||||
|
||||
public override string ToString() {
|
||||
var sb = new StringBuilder();
|
||||
sb.Append("class Order {\n");
|
||||
|
@ -2,42 +2,42 @@ using System;
|
||||
using System.Text;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
namespace io.swagger.Model {
|
||||
[DataContract]
|
||||
public class Pet {
|
||||
|
||||
|
||||
|
||||
[DataMember(Name="id", EmitDefaultValue=false)]
|
||||
public long? Id { get; set; }
|
||||
|
||||
|
||||
|
||||
|
||||
[DataMember(Name="category", EmitDefaultValue=false)]
|
||||
public Category Category { get; set; }
|
||||
|
||||
|
||||
|
||||
|
||||
[DataMember(Name="name", EmitDefaultValue=false)]
|
||||
public string Name { get; set; }
|
||||
|
||||
|
||||
|
||||
|
||||
[DataMember(Name="photoUrls", EmitDefaultValue=false)]
|
||||
public List<string> PhotoUrls { get; set; }
|
||||
|
||||
|
||||
|
||||
|
||||
[DataMember(Name="tags", EmitDefaultValue=false)]
|
||||
public List<Tag> Tags { get; set; }
|
||||
|
||||
|
||||
|
||||
/* pet status in the store */
|
||||
|
||||
[DataMember(Name="status", EmitDefaultValue=false)]
|
||||
public string Status { get; set; }
|
||||
|
||||
|
||||
|
||||
public override string ToString() {
|
||||
var sb = new StringBuilder();
|
||||
sb.Append("class Pet {\n");
|
||||
|
@ -2,21 +2,22 @@ using System;
|
||||
using System.Text;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
namespace io.swagger.Model {
|
||||
[DataContract]
|
||||
public class Tag {
|
||||
|
||||
|
||||
|
||||
[DataMember(Name="id", EmitDefaultValue=false)]
|
||||
public long? Id { get; set; }
|
||||
|
||||
|
||||
|
||||
|
||||
[DataMember(Name="name", EmitDefaultValue=false)]
|
||||
public string Name { get; set; }
|
||||
|
||||
|
||||
|
||||
public override string ToString() {
|
||||
var sb = new StringBuilder();
|
||||
sb.Append("class Tag {\n");
|
||||
|
@ -2,52 +2,52 @@ using System;
|
||||
using System.Text;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
namespace io.swagger.Model {
|
||||
[DataContract]
|
||||
public class User {
|
||||
|
||||
|
||||
|
||||
[DataMember(Name="id", EmitDefaultValue=false)]
|
||||
public long? Id { get; set; }
|
||||
|
||||
|
||||
|
||||
|
||||
[DataMember(Name="username", EmitDefaultValue=false)]
|
||||
public string Username { get; set; }
|
||||
|
||||
|
||||
|
||||
|
||||
[DataMember(Name="firstName", EmitDefaultValue=false)]
|
||||
public string FirstName { get; set; }
|
||||
|
||||
|
||||
|
||||
|
||||
[DataMember(Name="lastName", EmitDefaultValue=false)]
|
||||
public string LastName { get; set; }
|
||||
|
||||
|
||||
|
||||
|
||||
[DataMember(Name="email", EmitDefaultValue=false)]
|
||||
public string Email { get; set; }
|
||||
|
||||
|
||||
|
||||
|
||||
[DataMember(Name="password", EmitDefaultValue=false)]
|
||||
public string Password { get; set; }
|
||||
|
||||
|
||||
|
||||
|
||||
[DataMember(Name="phone", EmitDefaultValue=false)]
|
||||
public string Phone { get; set; }
|
||||
|
||||
|
||||
|
||||
/* User Status */
|
||||
|
||||
[DataMember(Name="userStatus", EmitDefaultValue=false)]
|
||||
public int? UserStatus { get; set; }
|
||||
|
||||
|
||||
|
||||
public override string ToString() {
|
||||
var sb = new StringBuilder();
|
||||
sb.Append("class User {\n");
|
||||
|
@ -1,19 +1,14 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using Newtonsoft.Json;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace io.swagger.client {
|
||||
namespace io.swagger.client {
|
||||
public class ApiInvoker {
|
||||
private static readonly ApiInvoker _instance = new ApiInvoker();
|
||||
private Dictionary<String, String> defaultHeaderMap = new Dictionary<String, String>();
|
||||
|
||||
public static ApiInvoker GetInstance() {
|
||||
return _instance;
|
||||
}
|
||||
private static Dictionary<String, String> defaultHeaderMap = new Dictionary<String, String>();
|
||||
|
||||
/// <summary>
|
||||
/// Add default header
|
||||
@ -21,16 +16,24 @@
|
||||
/// <param name="key"> Header field name
|
||||
/// <param name="value"> Header field value
|
||||
/// <returns></returns>
|
||||
public void addDefaultHeader(string key, string value) {
|
||||
public static void AddDefaultHeader(string key, string value) {
|
||||
defaultHeaderMap.Add(key, value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get default header
|
||||
/// </summary>
|
||||
/// <returns>Dictionary of default header</returns>
|
||||
public static Dictionary<String, String> GetDefaultHeader() {
|
||||
return defaultHeaderMap;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// escape string (url-encoded)
|
||||
/// </summary>
|
||||
/// <param name="str"> String to be escaped
|
||||
/// <returns>Escaped string</returns>
|
||||
public string escapeString(string str) {
|
||||
public static string EscapeString(string str) {
|
||||
return str;
|
||||
}
|
||||
|
||||
@ -39,7 +42,7 @@
|
||||
/// </summary>
|
||||
/// <param name="obj"> The parameter (header, path, query, form)
|
||||
/// <returns>Formatted string</returns>
|
||||
public string ParameterToString(object obj)
|
||||
public static string ParameterToString(object obj)
|
||||
{
|
||||
return (obj is DateTime) ? ((DateTime)obj).ToString ("u") : Convert.ToString (obj);
|
||||
}
|
||||
@ -50,7 +53,7 @@
|
||||
/// <param name="json"> JSON string
|
||||
/// <param name="type"> Object type
|
||||
/// <returns>Object representation of the JSON string</returns>
|
||||
public static object deserialize(string json, Type type) {
|
||||
public static object Deserialize(string json, Type type) {
|
||||
try
|
||||
{
|
||||
return JsonConvert.DeserializeObject(json, type);
|
||||
@ -58,10 +61,14 @@
|
||||
catch (IOException e) {
|
||||
throw new ApiException(500, e.Message);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static string serialize(object obj) {
|
||||
/// <summary>
|
||||
/// Serialize an object into JSON string
|
||||
/// </summary>
|
||||
/// <param name="obj"> Object
|
||||
/// <returns>JSON string</returns>
|
||||
public static string Serialize(object obj) {
|
||||
try
|
||||
{
|
||||
return obj != null ? JsonConvert.SerializeObject(obj) : null;
|
||||
@ -70,166 +77,5 @@
|
||||
throw new ApiException(500, e.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public string invokeAPI(string host, string path, string method, Dictionary<String, String> queryParams, object body, Dictionary<String, String> headerParams, Dictionary<String, object> formParams)
|
||||
{
|
||||
return invokeAPIInternal(host, path, method, false, queryParams, body, headerParams, formParams) as string;
|
||||
}
|
||||
|
||||
public byte[] invokeBinaryAPI(string host, string path, string method, Dictionary<String, String> queryParams, object body, Dictionary<String, String> headerParams, Dictionary<String, object> formParams)
|
||||
{
|
||||
return invokeAPIInternal(host, path, method, true, queryParams, body, headerParams, formParams) as byte[];
|
||||
}
|
||||
|
||||
private object invokeAPIInternal(string host, string path, string method, bool binaryResponse, Dictionary<String, String> queryParams, object body, Dictionary<String, String> headerParams, Dictionary<String, object> formParams) {
|
||||
var b = new StringBuilder();
|
||||
|
||||
foreach (var queryParamItem in queryParams)
|
||||
{
|
||||
var value = queryParamItem.Value;
|
||||
if (value == null) continue;
|
||||
b.Append(b.ToString().Length == 0 ? "?" : "&");
|
||||
b.Append(escapeString(queryParamItem.Key)).Append("=").Append(escapeString(value));
|
||||
}
|
||||
|
||||
var querystring = b.ToString();
|
||||
|
||||
host = host.EndsWith("/") ? host.Substring(0, host.Length - 1) : host;
|
||||
|
||||
var client = WebRequest.Create(host + path + querystring);
|
||||
client.Method = method;
|
||||
|
||||
byte[] formData = null;
|
||||
if (formParams.Count > 0)
|
||||
{
|
||||
string formDataBoundary = String.Format("----------{0:N}", Guid.NewGuid());
|
||||
client.ContentType = "multipart/form-data; boundary=" + formDataBoundary;
|
||||
formData = GetMultipartFormData(formParams, formDataBoundary);
|
||||
client.ContentLength = formData.Length;
|
||||
}
|
||||
else
|
||||
{
|
||||
client.ContentType = "application/json";
|
||||
}
|
||||
|
||||
foreach (var headerParamsItem in headerParams)
|
||||
{
|
||||
client.Headers.Add(headerParamsItem.Key, headerParamsItem.Value);
|
||||
}
|
||||
foreach (var defaultHeaderMapItem in defaultHeaderMap.Where(defaultHeaderMapItem => !headerParams.ContainsKey(defaultHeaderMapItem.Key)))
|
||||
{
|
||||
client.Headers.Add(defaultHeaderMapItem.Key, defaultHeaderMapItem.Value);
|
||||
}
|
||||
|
||||
switch (method)
|
||||
{
|
||||
case "GET":
|
||||
break;
|
||||
case "POST":
|
||||
case "PATCH":
|
||||
case "PUT":
|
||||
case "DELETE":
|
||||
using (Stream requestStream = client.GetRequestStream())
|
||||
{
|
||||
if (formData != null)
|
||||
{
|
||||
requestStream.Write(formData, 0, formData.Length);
|
||||
}
|
||||
|
||||
var swRequestWriter = new StreamWriter(requestStream);
|
||||
swRequestWriter.Write(serialize(body));
|
||||
swRequestWriter.Close();
|
||||
}
|
||||
break;
|
||||
default:
|
||||
throw new ApiException(500, "unknown method type " + method);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var webResponse = (HttpWebResponse)client.GetResponse();
|
||||
if (webResponse.StatusCode != HttpStatusCode.OK)
|
||||
{
|
||||
webResponse.Close();
|
||||
throw new ApiException((int)webResponse.StatusCode, webResponse.StatusDescription);
|
||||
}
|
||||
|
||||
if (binaryResponse)
|
||||
{
|
||||
using (var memoryStream = new MemoryStream())
|
||||
{
|
||||
webResponse.GetResponseStream().CopyTo(memoryStream);
|
||||
return memoryStream.ToArray();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
using (var responseReader = new StreamReader(webResponse.GetResponseStream()))
|
||||
{
|
||||
var responseData = responseReader.ReadToEnd();
|
||||
return responseData;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch(WebException ex)
|
||||
{
|
||||
var response = ex.Response as HttpWebResponse;
|
||||
int statusCode = 0;
|
||||
if (response != null)
|
||||
{
|
||||
statusCode = (int)response.StatusCode;
|
||||
response.Close();
|
||||
}
|
||||
throw new ApiException(statusCode, ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] GetMultipartFormData(Dictionary<string, object> postParameters, string boundary)
|
||||
{
|
||||
Stream formDataStream = new System.IO.MemoryStream();
|
||||
bool needsCLRF = false;
|
||||
|
||||
foreach (var param in postParameters)
|
||||
{
|
||||
// Thanks to feedback from commenters, add a CRLF to allow multiple parameters to be added.
|
||||
// Skip it on the first parameter, add it to subsequent parameters.
|
||||
if (needsCLRF)
|
||||
formDataStream.Write(Encoding.UTF8.GetBytes("\r\n"), 0, Encoding.UTF8.GetByteCount("\r\n"));
|
||||
|
||||
needsCLRF = true;
|
||||
|
||||
if (param.Value is byte[])
|
||||
{
|
||||
string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n",
|
||||
boundary,
|
||||
param.Key,
|
||||
"application/octet-stream");
|
||||
formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData));
|
||||
|
||||
// Write the file data directly to the Stream, rather than serializing it to a string.
|
||||
formDataStream.Write((param.Value as byte[]), 0, (param.Value as byte[]).Length);
|
||||
}
|
||||
else
|
||||
{
|
||||
string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}",
|
||||
boundary,
|
||||
param.Key,
|
||||
param.Value);
|
||||
formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData));
|
||||
}
|
||||
}
|
||||
|
||||
// Add the end of the request. Start with a newline
|
||||
string footer = "\r\n--" + boundary + "--\r\n";
|
||||
formDataStream.Write(Encoding.UTF8.GetBytes(footer), 0, Encoding.UTF8.GetByteCount(footer));
|
||||
|
||||
// Dump the Stream into a byte[]
|
||||
formDataStream.Position = 0;
|
||||
byte[] formData = new byte[formDataStream.Length];
|
||||
formDataStream.Read(formData, 0, formData.Length);
|
||||
formDataStream.Close();
|
||||
|
||||
return formData;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user