C#错误401 - 用户名或密码无效

时间:2016-08-01 13:41:04

标签: c# asp.net web-services rest http-status-code-401

我试图向API发出请求。 当我使用邮递员提出请求时,它有效。但是在c#中,它没有,它返回错误401。 我查了一下,登录和密码都是对的。 任何人都可以帮助我吗?

代码:

public JsonResult Test()
{
    var document = new HtmlAgilityPack.HtmlDocument();

    var password = CalculateMD5Hash("******");

    var httpRequest =(HttpWebRequest)WebRequest.Create(string.Format("https://api.akna.com.br/emkt/int/integracao.php?User={0}&Pass={1}&XML={2}",
    "mail@mail.com",
     password,
    @"<main>
    <emkt trans='19.10'>
    <datainicial>2016-07-01 10:00:00</datainicial>
    <datafinal>2016-07-02 10:00:00</datafinal>
    </emkt>
    </main>"));

    httpRequest.Method = "POST";
    httpRequest.ContentType = "application/x-www-form-urlencoded";

    try
    {
    var httpWebResponse = (HttpWebResponse)httpRequest.GetResponse();

    var responseStream = httpWebResponse.GetResponseStream();

    if (responseStream != null)
    {
     var sr = new StreamReader(responseStream, Encoding.Default);
     document.LoadHtml(sr.ReadToEnd());
   }

   return Json(new { StatusCode = 200 }, JsonRequestBehavior.AllowGet);
   }
  catch (Exception ex)
  {
  return Json(new { StatusCode = 500, Erro = ex.Message }, JsonRequestBehavior.AllowGet);
 }
 }

1 个答案:

答案 0 :(得分:0)

问题在于参数的编码。它解决了这个问题:http://rest.elkstein.org/2008/02/using-rest-in-c-sharp.html