CSharp: Close the WebResponse if we throw an ApiException

This commit is contained in:
Timothy Lusk 2014-07-15 15:19:13 -04:00
parent 527c40b996
commit 3b6ffa4a1f

View File

@ -14,7 +14,7 @@
public static ApiInvoker GetInstance() { public static ApiInvoker GetInstance() {
return _instance; return _instance;
} }
public void addDefaultHeader(string key, string value) { public void addDefaultHeader(string key, string value) {
defaultHeaderMap.Add(key, value); defaultHeaderMap.Add(key, value);
} }
@ -46,7 +46,7 @@
public string invokeAPI(string host, string path, string method, Dictionary<String, String> queryParams, object body, Dictionary<String, String> headerParams) { public string invokeAPI(string host, string path, string method, Dictionary<String, String> queryParams, object body, Dictionary<String, String> headerParams) {
var b = new StringBuilder(); var b = new StringBuilder();
foreach (var queryParamItem in queryParams) foreach (var queryParamItem in queryParams)
{ {
var value = queryParamItem.Value; var value = queryParamItem.Value;
@ -71,7 +71,7 @@
{ {
client.Headers.Add(defaultHeaderMapItem.Key, defaultHeaderMapItem.Value); client.Headers.Add(defaultHeaderMapItem.Key, defaultHeaderMapItem.Value);
} }
switch (method) switch (method)
{ {
case "GET": case "GET":
@ -84,13 +84,17 @@
swRequestWriter.Close(); swRequestWriter.Close();
break; break;
default: default:
throw new ApiException(500, "unknown method type " + method); throw new ApiException(500, "unknown method type " + method);
} }
try try
{ {
var webResponse = (HttpWebResponse)client.GetResponse(); var webResponse = (HttpWebResponse)client.GetResponse();
if (webResponse.StatusCode != HttpStatusCode.OK) throw new ApiException((int)webResponse.StatusCode, webResponse.StatusDescription); if (webResponse.StatusCode != HttpStatusCode.OK)
{
webResponse.Close();
throw new ApiException((int)webResponse.StatusCode, webResponse.StatusDescription);
}
var responseReader = new StreamReader(webResponse.GetResponseStream()); var responseReader = new StreamReader(webResponse.GetResponseStream());
var responseData = responseReader.ReadToEnd(); var responseData = responseReader.ReadToEnd();
@ -104,6 +108,7 @@
if (response != null) if (response != null)
{ {
statusCode = (int)response.StatusCode; statusCode = (int)response.StatusCode;
response.Close();
} }
throw new ApiException(statusCode, ex.Message); throw new ApiException(statusCode, ex.Message);
} }