Skip to content

Instantly share code, notes, and snippets.

@rmueller
Created September 9, 2015 19:16
Show Gist options
  • Save rmueller/0a88c5675a9bd4476b8a to your computer and use it in GitHub Desktop.
Save rmueller/0a88c5675a9bd4476b8a to your computer and use it in GitHub Desktop.
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