Created
September 9, 2015 19:16
-
-
Save rmueller/0a88c5675a9bd4476b8a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class WebApiClient | |
{ | |
private HttpWebRequest httpWebRequest; | |
public WebApiClient(Uri uri, int timeOut) | |
{ | |
httpWebRequest = CreateHttpWebRequest(uri, timeOut); | |
} | |
public string Post(string conteudo) | |
{ | |
byte[] bytes = Encoding.UTF8.GetBytes(conteudo); | |
httpWebRequest.ContentLength = bytes.Length; | |
httpWebRequest.Method = "POST"; | |
RunRequest(bytes); | |
return GetAnswer(); | |
} | |
private HttpWebRequest CreateHttpWebRequest(Uri uri, int timeOut) | |
{ | |
httpWebRequest = (HttpWebRequest)WebRequest.Create(uri); | |
httpWebRequest.ContentType = "text/plain; charset=UTF-8"; | |
httpWebRequest.KeepAlive = false; | |
httpWebRequest.Timeout = timeOut * 1000; | |
httpWebRequest.ServicePoint.Expect100Continue = false; | |
return httpWebRequest; | |
} | |
private void RunRequest(byte[] content) | |
{ | |
using (var stream = httpWebRequest.GetRequestStream()) | |
{ | |
stream.Write(content, 0, content.Length); | |
} | |
} | |
private string GetAnswer() | |
{ | |
using (var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse()) | |
{ | |
using (var responseStream = httpResponse.GetResponseStream()) | |
{ | |
if (responseStream == null) | |
throw new NullReferenceException("responseStream"); | |
using (var streamReader = new StreamReader(responseStream)) | |
{ | |
return streamReader.ReadToEnd(); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment