如何使用multipart / formdata编码和POST方法使用带有用户名和密码的rest API

时间:2019-01-28 06:37:20

标签: c# restful-authentication

我正在尝试使用以下API:https://clbeta.ecomexpress.in/apiv2/pincodes/。 我能够从邮递员工具获得输出。但无法从我创建的C#应用​​程序中获取结果。这些概念对我来说是陌生的,请为此提供帮助。

我也尝试过使用基本身份验证方法,但无法获得结果。

using System;
using System.IO;
using System.Net;
using RestSharp;
using Newtonsoft.Json;
namespace Ecomapisample
{

    public enum Httpverb
    {
        GET,
        POST,
        PUT,
        DELETE
    }

    public enum AuthenticationType
    {
        Basic,
        NTLM
    }
    class Ecomapi
    {
        public string EndPoint { get; set; }
        public Httpverb HttpMethod { get; set; }
        public AutheticationTechnique AuthTech { get; set; }
        public AuthenticationType AuthType { get; set; }
        public string UserName { get; set; }
        public string UserPassword { get; set; }

        public Ecomapi()
        {
            EndPoint = string.Empty;
            HttpMethod = Httpverb.POST;
        }




        public string MakeRequest()
        {
            string strResponseValue = string.Empty;
            HttpWebRequest request =(HttpWebRequest)WebRequest.Create(EndPoint);

            request.Method = HttpMethod.ToString();

            request.ContentType = "application/json";

            request.CookieContainer = new CookieContainer();

            string AuthHeader =  System.Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(UserName + ":" + UserPassword));
            request.Headers.Add(HttpRequestHeader.Authorization,AuthType.ToString() + AuthHeader);
            HttpWebResponse response = null;
            try
            {
                response = (HttpWebResponse)request.GetResponse();
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    throw new ApplicationException("Error code in response recieved: " + response.StatusCode.ToString());
                }

                else
                {

                    using (Stream responseStream = response.GetResponseStream())
                    {
                        if (responseStream != null)
                        {
                            using (StreamReader reader = new StreamReader(responseStream))
                            {
                                strResponseValue = reader.ReadToEnd();
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                strResponseValue = "{\"errorMessages\":[\"" + ex.Message.ToString() + "\"],\"errors\":{}}";
            }
            finally
            {
                if (response != null)
                {
                    ((IDisposable)response).Dispose();
                }
            }
            return strResponseValue;
        }
    }
}

//邮递员工具中的代码如下。

var client = new 
RestClient("https://clbeta.ecomexpress.in/apiv2/pincodes/");
var request = new RestRequest(Method.POST);
request.AddHeader("Postman-Token", "xxxxxxxxxxxxxxxx");
request.AddHeader("cache-control", "no-cache");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("content-type", "multipart/form-data; boundary=---- 
WebKitFormBoundary7MA4YWxkTrZu0gW");
request.AddParameter("multipart/form-data; boundary=---- 
WebKitFormBoundary7MA4YWxkTrZu0gW", "------ 
WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; 
name=\"username\"\r\n\r\xxxxxxxxxxxxxxxxxx\r\n------ 
WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; 
name=\"password\"\r\n\r\xxxxxxxxxxxxxxxxxxx\r\n------ 
WebKitFormBoundary7MA4YWxkTrZu0gW--", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);

我需要的输出是JSON输出。请帮忙。

1 个答案:

答案 0 :(得分:0)

这取决于API的编写方式,但是您可能想要尝试告诉它您接受什么。某些API并非默认为JSON,因此您必须通过提供另一个标头向它们发出信号。

request.AddHeader("Accept", "application/json");