Skip to content

Instantly share code, notes, and snippets.

@Whistler092
Created April 28, 2017 22:54
Show Gist options
  • Save Whistler092/d8feb4945fe12c010d078ce13b543ea4 to your computer and use it in GitHub Desktop.
Save Whistler092/d8feb4945fe12c010d078ce13b543ea4 to your computer and use it in GitHub Desktop.
Formas de hacer un http request con C#
using (var client = new WebClient())
{
ServicePointManager.Expect100Continue = false;
try
{
var values = new NameValueCollection();
values["id"] = id;
values["k"] = k;
values["s"] = s;
client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
var response = client.UploadValues(URLApi + "/Clients/", values);
v = Encoding.UTF8.GetString(response);
licInfo = JsonConvert.DeserializeObject<LicInfo>(v);
}
catch (WebException wex)
{
var response = wex.Response as HttpWebResponse;
if (response != null && response.StatusCode == HttpStatusCode.BadRequest)
{
Log("El servidor remoto respondió Bad Request:" wex.ToString());
using (var reader = new StreamReader(wex.Response.GetResponseStream()))
{
var responseText = reader.ReadToEnd();
if (!string.IsNullOrEmpty(responseText))
{
LicInfo result = JsonConvert.DeserializeObject<LicInfo>(responseText);
Log(result.message);
}
}
}
if (!string.IsNullOrEmpty(wex.Message))
Log(wex.Message);
}
catch (Exception ex)
{
Log(ex.ToString());
}
}
public class v2
{
internal static ResponseBindingModel Request(InstancesCloud k, string serviceURL, string ApiPath)
{
try
{
/*
How to used!
http://restsharp.org/
*/
var client = new RestClient(ServiceURL);
var request = new RestRequest(ApiPath, Method.POST);
request.AddHeader("accept", "application/json");
request.AddHeader("content-type", "application/json");
request.AddParameter("application/json", JsonConvert.SerializeObject(k), ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
if (!string.IsNullOrEmpty(response.ErrorMessage))
return "Error en el API De " + ApiPath + ". Detalle " + response.ErrorMessage;
if (response.StatusCode.Equals(HttpStatusCode.BadRequest) || response.StatusCode.Equals(HttpStatusCode.InternalServerError))
return "Error en el API De " + ApiPath + ". Detalle " + response.Content;
if (response.StatusCode.Equals(HttpStatusCode.OK))
return JsonConvert.DeserializeObject<ResponseBindingModel>(response.Content).ToString();
return new ResponseBindingModel { error = "Error al Consultar el API De " + ApiPath + "." };
}
catch (Exception ex)
{
return new ResponseBindingModel { error = "Error al Consultar el API De " + ApiPath + ". Detalle " + ex.ToString() };
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment