How do i get this webservice to work

When i run the following code, it does not work. I receive an unhandled exception of type system.net webexception occurred in system.dll

Can someone help me out to just make a simple JSON webrequest as decribed here:
 public static string getAuthenticationKey()
        {
            var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://api-gw.dhlparcel.nl/authenticate/api-key");
            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Accept = "application/json";
            httpWebRequest.Method = "POST";

            
            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                string json = "{" +
                                  " \"userId\": \"872ffb4f-c6d4-4ace-a972-c12959f7131c\", " +
                                  "\"key\": \"ee40c9a1-718c-4b48-a62f-e72835add906\"}";

                streamWriter.Write(json);
            }
            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var responseText = streamReader.ReadToEnd();
                //Now you have your response.
                //or false depending on information in the response
                return responseText;
            }
        }

Open in new window

Edward van NijmweegenICT employeeAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

ambienceCommented:
Would help if you could post the details of exception including stack trace and any other related information. Are you able to debug the code find out the exact point where it throws the exception?
it_saigeDeveloperCommented:
In other words, try this and post the results:
using System;
using System.IO;
using System.Net;
// Need to add a reference to System.Web.Extensions
using System.Web.Script.Serialization;

namespace EE_Q29084314
{
    class Program
    {
        static void Main(string[] args)
        {
            var authKey = GetAuthenticationKey();
            if (!string.IsNullOrWhiteSpace(authKey))
                Console.WriteLine($"Success: {authKey}");
            else
                Console.WriteLine("Authentication Failed!!!");
            Console.ReadLine();
        }

        static string GetAuthenticationKey()
        {
            var request = WebRequest.Create("https://api-gw.dhlparcel.nl/authenticate/api-key").AsHttpWebRequest();
            try
            {
                using (var writer = new StreamWriter(request.GetRequestStream()))
                {
                    string json = new JavaScriptSerializer().Serialize(new { userId = "872ffb4f-c6d4-4ace-a972-c12959f7131c", key = "ee40c9a1-718c-4b48-a62f-e72835add906" });
                    writer.Write(json);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Exception during request: {ex} [{ex.Message}]{Environment.NewLine}{ex.StackTrace}");
            }

            try
            {
                var response = request.GetResponse() as HttpWebResponse;
                using (var reader = new StreamReader(response.GetResponseStream()))
                {
                    var text = reader.ReadToEnd();
                    return text;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Exception during response: {ex} [{ex.Message}]{Environment.NewLine}{ex.StackTrace}");
            }
            return string.Empty;
        }
    }

    static class Extensions
    {
        public static HttpWebRequest AsHttpWebRequest(this WebRequest request)
        {
            HttpWebRequest result = request as HttpWebRequest;
            result.ContentType = "application/json";
            result.Accept = "application/json";
            result.Method = "POST";
            return result;
        }
    }
}

Open in new window


-saige-
Edward van NijmweegenICT employeeAuthor Commented:
Hello Saige,

Thanks for your help. The error is in Dutch, so i tried to translate it.

ex.Message = "The underlying connection is closed: An unexpected error has occurred during transmission."

ex.StackTrace = "   bij System.Net.HttpWebRequest.GetResponse()
   bij DHL_Label.Program.GetAuthenticationKey() in c:\Users\edward\Documents\Visual Studio 2013\Samples\test\schooladmin\SCHOOLADMIN\DHL_Label\Program.cs:regel 48"

Hope this makes it more clear.

Thanks,

Edward
Introduction to R

R is considered the predominant language for data scientist and statisticians. Learn how to use R for your own data science projects.

it_saigeDeveloperCommented:
The important bits are missing...  Just post the whole exception untranslated.  ;)

-saige-
ambienceCommented:
Have you made sure that the URL is accessible and working from the machine?
Edward van NijmweegenICT employeeAuthor Commented:
Saige,

With your piece of code, it already worked. I now get a result that i can use, thanks a lot for that. One other next this is that i now have to use the result to do the actual request. The result of the first request is a token for my new request.

How do i get this token in the new request?

I tried the following:
    
 public class DHLAccesCode
    {
        public string accessToken { get; set; }
        public int accessTokenExpiration { get; set; }
        public string refreshToken { get; set; }
        public int refreshTokenExpiration { get; set; }
    }




    public class DHLLabel
    {
        public string labelId { get; set; }
        public string labelType { get; set; }
        public string trackerCode { get; set; }
        public string routingCode { get; set; }
        public string userId { get; set; }
        public string organizationId { get; set; }
        public string orderReference { get; set; }
        public string zpl { get; set; }
        public string application { get; set; }
    }




    class DHLAuth
    {
        private string auth_Key = "";  // Backing store

        public string Auth_Key
        {
            get
            {
                return auth_Key;
            }
            set
            {
                auth_Key = value;
            }
        }
    }



 static string  GetDHLLabel(DHLAuth authKey)
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
          
            var request = WebRequest.Create("https://api-gw.dhlparcel.nl/labels").AsHttpWebRequestLabel(authKey);
            try
            {
                using (var writer = new StreamWriter(request.GetRequestStream()))
                {
                    string json = "{ \"labelId\": \"" + Guid.NewGuid().ToString()  + "\",  " +
                                   "\"labelFormat\": \"zpl\", " +
                                   "\"orderReference\": \"myReference\", " +
                                   "\"parcelTypeKey\": \"SMALL\", " +
                                   "\"receiver\": { " +
                                   "\"name\": { " +
                                   "\"firstName\": \"Jan\", " +
                                   "\"lastName\": \"Jansen\", " +
                                   "\"additionalName\": \"Benelux\" , " +
                                   "}," +
                                   "\"address\": { " +
                                   "\"countryCode\": \"NL\", " +
                                   "\"postalCode\": \"3542AD\"," +
                                   "\"city\": \"Utrecht\", " +
                                   "\"street\": \"Reactorweg\", " +
                                   "\"number\": \"25\",  " +
                                   "\"isBusiness\": true," +
                                   "\"addition\": \"A\"" +
                                   "}," +
                                   "\"email\": \"mrparcel@dhlparcel.nl\"," +
                                   "\"phoneNumber\": \"0031612345678\" " +
                                   "}," +
                                   "\"shipper\": {    " +
                                   "\"name\": { " +
                                   "\"firstName\": \"John\", " +
                                   "\"companyName\": \"ACME Corp.\", " +
                                   "\"additionalName\": \"Benelux\"" +
                                   "}, " +
                                   "\"address\": {  " +
                                   "\"countryCode\": \"NL\", " +
                                   "\"additionalName\": \"Benelux\"" +
                                   "\"postalCode\": \"3542AD\"," +
                                   "\"city\": \"Utrecht\"," +
                                   "\"street\": \"Reactorweg\"," +
                                   "\"number\": \"25\"," +
                                   "\"isBusiness\": true," +
                                   "\"addition\": \"A\" " +
                                    "}, " +
                                   "\"email\": \"mrparcel@dhlparcel.nl\", " +
                                   "\"phoneNumber\": \"0031612345678\"" +
                                     "}, " +
                                   "\"options\": [{      \"key\": \"DOOR\"    }  ], " +
                                   "\"returnLabel\": false, " +
                                   "\"pieceNumber\": 1,  " +
                                   "\"quantity\": 1," +
                                   "\"automaticPrintDialog\": true," +
                                   "\"application\": \"string\"}";


                    writer.Write(json);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Exception during request: " + ex + " message: " + ex.Message);
            }
        
            return request.ToString();


          
        }



        public static HttpWebRequest AsHttpWebRequestLabel(this WebRequest request, DHLAuth authKey)
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                        HttpWebRequest result = request as HttpWebRequest;
            result.ContentType = "application/json";
            result.PreAuthenticate = true;
            result.KeepAlive = false;
            result.Headers.Add("Authorization", "Bearer :" + authKey.Auth_Key.ToString());
            result.Accept = "application/json";
            result.Method = "POST";
            return result;
            
        }

Open in new window

ambienceCommented:
Is that the whole code? Its probably working because you arent even reading the response. Can you post the entire code or at least the missing part? The following for example

            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var responseText = streamReader.ReadToEnd();
                //Now you have your response.
                //or false depending on information in the response
                return responseText;
            }

Open in new window

Edward van NijmweegenICT employeeAuthor Commented:
Hello,

Bellow is my whole code. I know that the json string for the label request is not ideale, but i don't know how to do the child records in json.
using System;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Web.Script.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace VHV_DHL_AXLabels
{
  

    public partial class Form1 : Form
    {
       
        public Form1()
        {
            InitializeComponent();
            textBox1.Text = "Start";
        }

        private void button1_Click(object sender, EventArgs e)
        {

            var authKey = GetAuthenticationKey();
            DHLAccesCode deserializedProduct = JsonConvert.DeserializeObject<DHLAccesCode>(authKey);


            if (!string.IsNullOrWhiteSpace(authKey))
            {
                System.DateTime startdt =  new DateTime(1970, 1, 1);
                System.TimeSpan duration = new System.TimeSpan(0, 0, 0, deserializedProduct.accessTokenExpiration);
                System.DateTime answer = startdt.Add(duration);

                txtAuthkey.Text = deserializedProduct.accessToken ;
                txtAuthExpire.Text = answer.ToString();
                DHLAuth keyAuth = new DHLAuth();
                keyAuth.Auth_Key = deserializedProduct.accessToken;

                textBox1.Text = "Success: " + authKey;
                Application.DoEvents();

                
                var resultLabel = GetDHLLabel(keyAuth);

            }
            else
            {
                textBox1.Text = "Authentication Failed!!!";

            }


      
        }


        static string GetAuthenticationKey()
        {
           // ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
            var request = WebRequest.Create("https://api-gw.dhlparcel.nl/authenticate/api-key").AsHttpWebRequest();
            try
            {
                using (var writer = new StreamWriter(request.GetRequestStream()))
                {
                    string json = new JavaScriptSerializer().Serialize(new { userId = "872ffb4f-c6d4-4ace-a972-c12959f7131c", key = "ee40c9a1-718c-4b48-a62f-e72835add906" });
                    writer.Write(json);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Exception during request: " + ex + " message: " + ex.Message);
            }

            try
            {
                var response = request.GetResponse() as HttpWebResponse;
                using (var reader = new StreamReader(response.GetResponseStream()))
                {
                    var text = reader.ReadToEnd();
                    return text;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Exception during response: " + ex.Message);
            }
            return string.Empty;
        }

        static string  GetDHLLabel(DHLAuth authKey)
        {
            ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
            var request = WebRequest.Create("https://api-gw.dhlparcel.nl/labels").AsHttpWebRequestLabel(authKey);
            try
            {
                using (var writer = new StreamWriter(request.GetRequestStream()))
                {

                    string json = "{ \"labelId\": \"" + Guid.NewGuid().ToString()+ "\",  " +
                                  "\"labelFormat\": \"zpl\", " +
                                  "\"orderReference\": \"myReference\", " +
                                  "\"parcelTypeKey\": \"SMALL\", " +
                                  "\"receiver\": { " +
                                  "\"name\": { " +
                                  "\"firstName\": \"Jan\", " +
                                  "\"lastName\": \"Jansen\", " +
                                  "\"additionalName\": \"Benelux\" , " +
                                  "}," +
                                  "\"address\": { " +
                                  "\"countryCode\": \"NL\", " +
                                  "\"postalCode\": \"3542AD\"," +
                                  "\"city\": \"Utrecht\", " +
                                  "\"street\": \"Reactorweg\", " +
                                  "\"number\": \"25\",  " +
                                  "\"isBusiness\": true," +
                                  "\"addition\": \"A\"" +
                                  "}," +
                                  "\"email\": \"mrparcel@dhlparcel.nl\"," +
                                  "\"phoneNumber\": \"0031612345678\" " +
                                  "}," +
                                  "\"shipper\": {    " +
                                  "\"name\": { " +
                                  "\"firstName\": \"John\", " +
                                  "\"companyName\": \"ACME Corp.\", " +
                                  "\"additionalName\": \"Benelux\"" +
                                  "}, " +
                                  "\"address\": {  " +
                                  "\"countryCode\": \"NL\", " +
                                  "\"additionalName\": \"Benelux\"" +
                                  "\"postalCode\": \"3542AD\"," +
                                  "\"city\": \"Utrecht\"," +
                                  "\"street\": \"Reactorweg\"," +
                                  "\"number\": \"25\"," +
                                  "\"isBusiness\": true," +
                                  "\"addition\": \"A\" " +
                                   "}, " +
                                  "\"email\": \"mrparcel@dhlparcel.nl\", " +
                                  "\"phoneNumber\": \"0031612345678\"" +
                                    "}, " +
                                  "\"options\": [{      \"key\": \"DOOR\"    }  ], " +
                                  "\"returnLabel\": false, " +
                                  "\"pieceNumber\": 1,  " +
                                  "\"quantity\": 1," +
                                  "\"automaticPrintDialog\": true," +
                                  "\"application\": \"string\"}";



                    writer.Write(json);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Exception during request: " + ex + " message: " + ex.Message);
            }

            try
            {
                var response = request.GetResponse() as HttpWebResponse;
                using (var reader = new StreamReader(response.GetResponseStream()))
                {
                    var text = reader.ReadToEnd();
                    return text;
                }
            }
            catch (WebException ex)
            {
                if (ex.Response != null)
                {
                    using (var errorResponse = (HttpWebResponse)ex.Response)
                    {
                        using (var reader = new StreamReader(errorResponse.GetResponseStream()))
                        {
                            string error = reader.ReadToEnd();
                           return error;
                        }
                    }
                }
                return  "Exception during response: " + ex.Message;
            }
            return string.Empty;
        }

    
       



    }


    public class DHLAccesCode
    {
        public string accessToken { get; set; }
        public int accessTokenExpiration { get; set; }
        public string refreshToken { get; set; }
        public int refreshTokenExpiration { get; set; }
    }

    public class DHLLabel
    {
        public string labelId { get; set; }
        public string labelType { get; set; }
        public string trackerCode { get; set; }
        public string routingCode { get; set; }
        public string userId { get; set; }
        public string organizationId { get; set; }
        public string orderReference { get; set; }
        public string zpl { get; set; }
        public string application { get; set; }
    }

    public class DHLLabelRequest
    {
        public string labelId { get; set; }
        public string labelFormat { get; set; }
        public string orderReference { get; set; }
        public string parcelTypeKey { get; set; }
        public string receiver { get; set; }
        public string receivername { get; set; }
        public string receivernamefirstName { get; set; }
        public string receivernamelastName { get; set; }
        public string receivernameadditionalName { get; set; }
        public string receiveraddress { get; set; }
        public string receiveraddresscountryCode { get; set; }
        public string receiveraddresspostalCode { get; set; }
        public string receiveraddresscity { get; set; }
        public string receiveraddressstreet { get; set; }
        public string receiveraddressnumber { get; set; }
        public string receiveraddressisBusiness { get; set; }
        public string receiveraddressaddition { get; set; }
        public string receiveremail { get; set; }
        public string receiverphoneNumber { get; set; }
        public string shipper { get; set; }
        public string shippername { get; set; }
        public string shippernamefirstName { get; set; }
        public string shippernamecompanyName { get; set; }
        public string shippernameadditionalName { get; set; }
        public string shipperaddress { get; set; }
        public string shipperaddresscountryCode { get; set; }
        public string shipperaddressadditionalName { get; set; }
        public string shipperaddresspostalCode { get; set; }
        public string shipperaddresscity { get; set; }
        public string shipperaddressstreet { get; set; }
        public string shipperaddressnumber { get; set; }
        public string shipperaddressisBusiness { get; set; }
        public string shipperaddressaddition { get; set; }
        public string shipperemail { get; set; }
        public string shipperphoneNumber { get; set; }
        public string options { get; set; }
        public string optionskey { get; set; }
        public string returnLabel { get; set; }
        public string pieceNumber { get; set; }
        public string quantity { get; set; }
        public string automaticPrintDialog { get; set; }
        public string application { get; set; }
     
    }





    class DHLAuth
    {
        private string auth_Key = "";  // Backing store

        public string Auth_Key
        {
            get
            {
                return auth_Key;
            }
            set
            {
                auth_Key = value;
            }
        }
    }

   

    static class Extensions
    {
       
        public static HttpWebRequest AsHttpWebRequest(this WebRequest request)
        {
            //ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;

            HttpWebRequest result = request as HttpWebRequest;
            result.ContentType = "application/json";
            result.PreAuthenticate = true;
            result.KeepAlive = false;
            result.Accept = "application/json";
            result.Method = "POST";
            return result;
        }


        public static HttpWebRequest AsHttpWebRequestLabel(this WebRequest request, DHLAuth authKey)
        {
            ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
            HttpWebRequest result = request as HttpWebRequest;
            result.ContentType = "application/json";
            result.Headers.Add("Authorization", "Bearer " + authKey.Auth_Key.ToString());
            result.PreAuthenticate = true;
            result.KeepAlive = false;
            result.Accept = "application/json";
            result.Method = "POST";
            return result;
        }



        



        }
    }

Open in new window



When i run this code, i receive the correct token, but when i do the label request i receive an 400 error, which is invalid task.
it_saigeDeveloperCommented:
Rather than trying to manually stringify the request object, simply create a new object or create a class, which can be serialized, to represent the object.  Let your Json helper methods stringify the objects you provide; e.g. -
using Newtonsoft.Json;
using System;
using System.IO;
using System.Net;

namespace EE_Q29084314
{
    class Program
    {
        static void Main(string[] args)
        {
            ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
            var authKey = PostAndGetResponse("authenticate/api-key", new AuthKey { UserId = "872ffb4f-c6d4-4ace-a972-c12959f7131c", Key = "ee40c9a1-718c-4b48-a62f-e72835add906" });
            if (!string.IsNullOrWhiteSpace(authKey))
            {
                var accessCode = JsonConvert.DeserializeObject<DHLAccessCode>(authKey);
                if (!string.IsNullOrWhiteSpace(accessCode.AccessToken))
                {
                    var data = new {
                        labelId = Guid.NewGuid().ToString(),
                        labelFormat = "zpl",
                        orderReference = "myReference",
                        parcelTypeKey = "SMALL",
                        receiver = new
                        {
                            name = new
                            {
                                firstName = "Jan",
                                lastName = "Jansen",
                                additionalName = "Benelux",
                            },
                            address = new
                            {
                                countryCode = "NL",
                                postalCode = "3542AD",
                                city = "Utrecht",
                                street = "Reactorweg",
                                number = "25",
                                isBusiness = true,
                                addition = "A"
                            },
                            email = "mrparcel@dhlparcel.nl",
                            phoneNumber = "0031612345678"
                        },
                        shipper = new
                        {
                            name = new
                            {
                                firstName = "John",
                                companyName = "ACME Corp.",
                                additionalName = "Benelux"
                            },
                            address = new
                            {
                                countryCode = "NL",
                                additionalName = "Benelux",
                                postalCode = "3542AD",
                                city = "Utrecht",
                                street = "Reactorweg",
                                number = "25",
                                isBusiness = true,
                                addition = "A"
                            },
                            email = "mrparcel@dhlparcel.nl",
                            phoneNumber = "0031612345678"
                        },
                        options = new[] { new { key = "DOOR" } },
                        returnLabel = false,
                        pieceNumber = 1,
                        quantity = 1,
                        automaticPrintDialog = true,
                        application = "string"
                    };
                    var dhlLabel = PostAndGetResponse("labels", data, accessCode.AccessToken);
                    if (!string.IsNullOrWhiteSpace(dhlLabel))
                    {
                        Console.WriteLine(dhlLabel);
                    }
                    else
                    {
                        Console.WriteLine("Failed to retrieve label");
                    }
                }
            }
            else
                Console.WriteLine("Authentication Failed!!!");

            Console.ReadLine();
        }

        static string PostAndGetResponse(string route, dynamic data, string accessToken = null)
        {
            var request = WebRequest.Create($"https://api-gw.dhlparcel.nl/{route}").AsHttpWebRequest(accessToken);
            try
            {
                using (var writer = new StreamWriter(request.GetRequestStream()))
                {
                    string json = JsonConvert.SerializeObject(data);
                    writer.Write(json);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Exception during request: {ex.Message}");
            }

            try
            {
                var response = request.GetResponse() as HttpWebResponse;
                using (var reader = new StreamReader(response.GetResponseStream()))
                {
                    var text = reader.ReadToEnd();
                    return text;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Exception during response: {ex.Message}");
            }
            return string.Empty;
        }
    }

    class AuthKey
    {
        public string UserId { get; set; }
        public string Key { get; set; }
    }

    class DHLAccessCode
    {
        public string AccessToken { get; set; }
        public int AccessTokenExpiration { get; set; }
        public string RefreshToken { get; set; }
        public int RefreshTokenExpiration { get; set; }
    }

    class DHLLabel
    {
        public string LabelId { get; set; }
        public string LabelType { get; set; }
        public string TrackerCode { get; set; }
        public string RoutingCode { get; set; }
        public string UserId { get; set; }
        public string OrganizationId { get; set; }
        public string OrderReference { get; set; }
        public string Zpl { get; set; }
        public string Application { get; set; }
    }

    class DHLLabelRequest
    {
        public string LabelId { get; set; }
        public string LabelFormat { get; set; }
        public string OrderReference { get; set; }
        public string ParcelTypeKey { get; set; }
        public string Receiver { get; set; }
        public string Receivername { get; set; }
        public string ReceivernamefirstName { get; set; }
        public string ReceivernamelastName { get; set; }
        public string ReceivernameadditionalName { get; set; }
        public string Receiveraddress { get; set; }
        public string ReceiveraddresscountryCode { get; set; }
        public string ReceiveraddresspostalCode { get; set; }
        public string Receiveraddresscity { get; set; }
        public string Receiveraddressstreet { get; set; }
        public string Receiveraddressnumber { get; set; }
        public string ReceiveraddressisBusiness { get; set; }
        public string Receiveraddressaddition { get; set; }
        public string Receiveremail { get; set; }
        public string ReceiverphoneNumber { get; set; }
        public string Shipper { get; set; }
        public string Shippername { get; set; }
        public string ShippernamefirstName { get; set; }
        public string ShippernamecompanyName { get; set; }
        public string ShippernameadditionalName { get; set; }
        public string Shipperaddress { get; set; }
        public string ShipperaddresscountryCode { get; set; }
        public string ShipperaddressadditionalName { get; set; }
        public string ShipperaddresspostalCode { get; set; }
        public string Shipperaddresscity { get; set; }
        public string Shipperaddressstreet { get; set; }
        public string Shipperaddressnumber { get; set; }
        public string ShipperaddressisBusiness { get; set; }
        public string Shipperaddressaddition { get; set; }
        public string Shipperemail { get; set; }
        public string ShipperphoneNumber { get; set; }
        public string Options { get; set; }
        public string Optionskey { get; set; }
        public string ReturnLabel { get; set; }
        public string PieceNumber { get; set; }
        public string Quantity { get; set; }
        public string AutomaticPrintDialog { get; set; }
        public string Application { get; set; }
    }

    static class Extensions
    {
        public static HttpWebRequest AsHttpWebRequest(this WebRequest request, string accessToken = null)
        {
            HttpWebRequest result = request as HttpWebRequest;
            result.ContentType = "application/json";
            result.Accept = "application/json";
            result.Method = "POST";

            if (accessToken != null)
                result.Headers.Add("Authorization", $"Bearer {accessToken}");

            return result;
        }
    }
}

Open in new window


-saige-
Edward van NijmweegenICT employeeAuthor Commented:
Hello Saige,

I tried the code, and the json request seem to be well formatted, but the final request failed with unknown command (error 400).
Ik also modified the code a bit, because the authentication didn't work.

If you run the code as copied below, you should get the error message as wel.

using Newtonsoft.Json;
using System;
using System.IO;
using System.Net;
using System.Data;
using System.Linq;
using System.Web.Script.Serialization;
using Newtonsoft.Json.Linq;

namespace DHLTest
{
    class Program
    {
        static void Main(string[] args)
        {
            ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
            //  var authKey = PostAndGetResponse("authenticate/api-key", new AuthKey { UserId = "872ffb4f-c6d4-4ace-a972-c12959f7131c", Key = "ee40c9a1-718c-4b48-a62f-e72835add906" });
            // Console.WriteLine("Key:" );

            var authKey = GetAuthenticationKey();
            DHLTest.DHLAccessCode  deserializedProduct = JsonConvert.DeserializeObject<DHLAccessCode>(authKey);


            if (!string.IsNullOrWhiteSpace(authKey))
            {
               
                Console.WriteLine("Authentication: " + deserializedProduct.AccessToken);

                authKey = deserializedProduct.AccessToken;
                
            }
            else
            {
                Console.WriteLine("Authentication Failed!!!");

            }






            if (!string.IsNullOrWhiteSpace(authKey))
            {
             //   var accessCode = JsonConvert.DeserializeObject<DHLAccessCode>(authKey);
              //  if (!string.IsNullOrWhiteSpace(accessCode.AccessToken))
              if (!string.IsNullOrWhiteSpace(authKey))
                {
                    var data = new
                    {
                        labelId = Guid.NewGuid().ToString(),
                        labelFormat = "zpl",
                        orderReference = "myReference",
                        parcelTypeKey = "SMALL",
                        receiver = new
                        {
                            name = new
                            {
                                firstName = "Jan",
                                lastName = "Jansen",
                                additionalName = "Benelux",
                            },
                            address = new
                            {
                                countryCode = "NL",
                                postalCode = "3542AD",
                                city = "Utrecht",
                                street = "Reactorweg",
                                number = "25",
                                isBusiness = true,
                                addition = "A"
                            },
                            email = "mrparcel@dhlparcel.nl",
                            phoneNumber = "0031612345678"
                        },
                        shipper = new
                        {
                            name = new
                            {
                                firstName = "John",
                                companyName = "ACME Corp.",
                                additionalName = "Benelux"
                            },
                            address = new
                            {
                                countryCode = "NL",
                                additionalName = "Benelux",
                                postalCode = "3542AD",
                                city = "Utrecht",
                                street = "Reactorweg",
                                number = "25",
                                isBusiness = true,
                                addition = "A"
                            },
                            email = "mrparcel@dhlparcel.nl",
                            phoneNumber = "0031612345678"
                        },
                        options = new[] { new { key = "DOOR" } },
                        returnLabel = false,
                        pieceNumber = 1,
                        quantity = 1,
                        automaticPrintDialog = true,
                        application = "string"
                    };
                    var dhlLabel = PostAndGetResponse("labels", data, authKey);
                    if (!string.IsNullOrWhiteSpace(dhlLabel))
                    {
                        Console.WriteLine(dhlLabel);
                    }
                    else
                    {
                        Console.WriteLine("Failed to retrieve label");
                    }
                }
            }
            else
                Console.WriteLine("Authentication Failed!!!");

            Console.ReadLine();
        }


        static string GetAuthenticationKey()
        {
            // ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
            var request = WebRequest.Create("https://api-gw.dhlparcel.nl/authenticate/api-key").AsHttpWebRequest();
            try
            {
                using (var writer = new StreamWriter(request.GetRequestStream()))
                {
                    string json = new JavaScriptSerializer().Serialize(new { userId = "872ffb4f-c6d4-4ace-a972-c12959f7131c", key = "ee40c9a1-718c-4b48-a62f-e72835add906" });
                    writer.Write(json);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception during request: " + ex + " message: " + ex.Message);
            }

            try
            {
                var response = request.GetResponse() as HttpWebResponse;
                using (var reader = new StreamReader(response.GetResponseStream()))
                {
                    var text = reader.ReadToEnd();
                    return text;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception during request: " + ex + " message: " + ex.Message);
            }
            return string.Empty;
        }
        static string PostAndGetResponse(string route, dynamic data, string accessToken = null)
        {
            var request = WebRequest.Create($"https://api-gw.dhlparcel.nl/{route}").AsHttpWebRequest(accessToken);
            try
            {
                using (var writer = new StreamWriter(request.GetRequestStream()))
                {
                    string json = JsonConvert.SerializeObject(data);
                    writer.Write(json);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Exception during request: {ex.Message}");
            }

            try
            {
                var response = request.GetResponse() as HttpWebResponse;
                using (var reader = new StreamReader(response.GetResponseStream()))
                {
                    var text = reader.ReadToEnd();
                    return text;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Exception during response: {ex.Message}");
            }
            return string.Empty;
        }
    }

    class AuthKey
    {
        public string UserId { get; set; }
        public string Key { get; set; }
    }

    class DHLAccessCode
    {
        public string AccessToken { get; set; }
        public int AccessTokenExpiration { get; set; }
        public string RefreshToken { get; set; }
        public int RefreshTokenExpiration { get; set; }
    }

    class DHLLabel
    {
        public string LabelId { get; set; }
        public string LabelType { get; set; }
        public string TrackerCode { get; set; }
        public string RoutingCode { get; set; }
        public string UserId { get; set; }
        public string OrganizationId { get; set; }
        public string OrderReference { get; set; }
        public string Zpl { get; set; }
        public string Application { get; set; }
    }

    class DHLLabelRequest
    {
        public string LabelId { get; set; }
        public string LabelFormat { get; set; }
        public string OrderReference { get; set; }
        public string ParcelTypeKey { get; set; }
        public string Receiver { get; set; }
        public string Receivername { get; set; }
        public string ReceivernamefirstName { get; set; }
        public string ReceivernamelastName { get; set; }
        public string ReceivernameadditionalName { get; set; }
        public string Receiveraddress { get; set; }
        public string ReceiveraddresscountryCode { get; set; }
        public string ReceiveraddresspostalCode { get; set; }
        public string Receiveraddresscity { get; set; }
        public string Receiveraddressstreet { get; set; }
        public string Receiveraddressnumber { get; set; }
        public string ReceiveraddressisBusiness { get; set; }
        public string Receiveraddressaddition { get; set; }
        public string Receiveremail { get; set; }
        public string ReceiverphoneNumber { get; set; }
        public string Shipper { get; set; }
        public string Shippername { get; set; }
        public string ShippernamefirstName { get; set; }
        public string ShippernamecompanyName { get; set; }
        public string ShippernameadditionalName { get; set; }
        public string Shipperaddress { get; set; }
        public string ShipperaddresscountryCode { get; set; }
        public string ShipperaddressadditionalName { get; set; }
        public string ShipperaddresspostalCode { get; set; }
        public string Shipperaddresscity { get; set; }
        public string Shipperaddressstreet { get; set; }
        public string Shipperaddressnumber { get; set; }
        public string ShipperaddressisBusiness { get; set; }
        public string Shipperaddressaddition { get; set; }
        public string Shipperemail { get; set; }
        public string ShipperphoneNumber { get; set; }
        public string Options { get; set; }
        public string Optionskey { get; set; }
        public string ReturnLabel { get; set; }
        public string PieceNumber { get; set; }
        public string Quantity { get; set; }
        public string AutomaticPrintDialog { get; set; }
        public string Application { get; set; }
    }

    static class Extensions
    {
        public static HttpWebRequest AsHttpWebRequest(this WebRequest request, string accessToken = null)
        {
            HttpWebRequest result = request as HttpWebRequest;
            result.ContentType = "application/json";
            result.Accept = "application/json";
            result.Method = "POST";

            if (accessToken != null)
                result.Headers.Add("Authorization", $"Bearer {accessToken}");

            return result;
        }
    }
}

Open in new window


Thanks,

Edward
it_saigeDeveloperCommented:
Your original data object didn't match up with the object that the api is expecting.  After correcting this is my result:
using Newtonsoft.Json;
using System;
using System.IO;
using System.Net;

namespace EE_Q29084314
{
    class Program
    {
        static void Main(string[] args)
        {
            ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
            var authKey = PostAndGetResponse("authenticate/api-key", new { userId = "872ffb4f-c6d4-4ace-a972-c12959f7131c", key = "ee40c9a1-718c-4b48-a62f-e72835add906" });
            if (!string.IsNullOrWhiteSpace(authKey))
            {
                var accessCode = JsonConvert.DeserializeObject<DHLAccessCode>(authKey);
                if (!string.IsNullOrWhiteSpace(accessCode.AccessToken))
                {
                    var data = new  {
                        labelId = Guid.NewGuid().ToString(),
                        labelFormat = "zpl",
                        orderReference = "myReference",
                        parcelTypeKey = "SMALL",
                        receiver = new {
                            name = new {
                                firstName = "Jan",
                                lastName = "Jansen",
                                companyName = "ACME Company",
                                additionalName = "Benelux",
                            },
                            address = new {
                                countryCode = "NL",
                                postalCode = "3542AD",
                                city = "Utrecht",
                                street = "Reactorweg",
                                number = "25",
                                isBusiness = true,
                                addition = "A"
                            },
                            email = "mrparcel@dhlparcel.nl",
                            phoneNumber = "0031612345678"
                        },
                        shipper = new {
                            name = new {
                                firstName = "John",
                                lastName = "Doe",
                                companyName = "ACME Corp.",
                                additionalName = "Benelux"
                            },
                            address = new {
                                countryCode = "NL",
                                postalCode = "3542AD",
                                city = "Utrecht",
                                street = "Reactorweg",
                                number = "25",
                                isBusiness = true,
                                addition = "A"
                            },
                            email = "mrparcel@dhlparcel.nl",
                            phoneNumber = "0031612345678"
                        },
                        accountId = "01234567",
                        options = new[] { new { key = "DOOR" } },
                        returnLabel = false,
                        pieceNumber = 1,
                        quantity = 1,
                        automaticPrintDialog = true,
                        application = "string"
                    };
                    var dhlLabel = PostAndGetResponse("labels", data, accessCode.AccessToken);
                    if (!string.IsNullOrWhiteSpace(dhlLabel))
                    {
                        Console.WriteLine(dhlLabel);
                    }
                    else
                    {
                        Console.WriteLine("Failed to retrieve label");
                    }
                }
            }
            else
                Console.WriteLine("Authentication Failed!!!");

            Console.ReadLine();
        }

        static string PostAndGetResponse(string route, dynamic data, string accessToken = null)
        {
            var request = WebRequest.Create($"https://api-gw.dhlparcel.nl/{route}").AsHttpWebRequest(accessToken);
            try
            {
                using (var writer = new StreamWriter(request.GetRequestStream()))
                {
                    string json = JsonConvert.SerializeObject(data);
                    writer.Write(json);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Exception during request: {ex.Message}");
            }

            try
            {
                var response = request.GetResponse() as HttpWebResponse;
                using (var reader = new StreamReader(response.GetResponseStream()))
                {
                    var text = reader.ReadToEnd();
                    return text;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Exception during response: {ex.Message}");
            }
            return string.Empty;
        }
    }

    class DHLAccessCode
    {
        public string AccessToken { get; set; }
        public int AccessTokenExpiration { get; set; }
        public string RefreshToken { get; set; }
        public int RefreshTokenExpiration { get; set; }
    }

    class DHLLabel
    {
        public string LabelId { get; set; }
        public string LabelType { get; set; }
        public string TrackerCode { get; set; }
        public string RoutingCode { get; set; }
        public string UserId { get; set; }
        public string OrganizationId { get; set; }
        public string OrderReference { get; set; }
        public string Zpl { get; set; }
        public string Application { get; set; }
    }

    class DHLLabelRequest
    {
        public string LabelId { get; set; }
        public string LabelFormat { get; set; }
        public string OrderReference { get; set; }
        public string ParcelTypeKey { get; set; }
        public string Receiver { get; set; }
        public string Receivername { get; set; }
        public string ReceivernamefirstName { get; set; }
        public string ReceivernamelastName { get; set; }
        public string ReceivernameadditionalName { get; set; }
        public string Receiveraddress { get; set; }
        public string ReceiveraddresscountryCode { get; set; }
        public string ReceiveraddresspostalCode { get; set; }
        public string Receiveraddresscity { get; set; }
        public string Receiveraddressstreet { get; set; }
        public string Receiveraddressnumber { get; set; }
        public string ReceiveraddressisBusiness { get; set; }
        public string Receiveraddressaddition { get; set; }
        public string Receiveremail { get; set; }
        public string ReceiverphoneNumber { get; set; }
        public string Shipper { get; set; }
        public string Shippername { get; set; }
        public string ShippernamefirstName { get; set; }
        public string ShippernamecompanyName { get; set; }
        public string ShippernameadditionalName { get; set; }
        public string Shipperaddress { get; set; }
        public string ShipperaddresscountryCode { get; set; }
        public string ShipperaddressadditionalName { get; set; }
        public string ShipperaddresspostalCode { get; set; }
        public string Shipperaddresscity { get; set; }
        public string Shipperaddressstreet { get; set; }
        public string Shipperaddressnumber { get; set; }
        public string ShipperaddressisBusiness { get; set; }
        public string Shipperaddressaddition { get; set; }
        public string Shipperemail { get; set; }
        public string ShipperphoneNumber { get; set; }
        public string Options { get; set; }
        public string Optionskey { get; set; }
        public string ReturnLabel { get; set; }
        public string PieceNumber { get; set; }
        public string Quantity { get; set; }
        public string AutomaticPrintDialog { get; set; }
        public string Application { get; set; }
    }

    static class Extensions
    {
        public static HttpWebRequest AsHttpWebRequest(this WebRequest request, string accessToken = null)
        {
            HttpWebRequest result = request as HttpWebRequest;
            result.ContentType = "application/json";
            result.Accept = "application/json";
            result.Method = "POST";

            if (accessToken != null)
                result.Headers.Add("Authorization", $"Bearer {accessToken}");

            return result;
        }
    }
}

Open in new window

Which produces the following partial output -Capture.PNG
-saige-

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Edward van NijmweegenICT employeeAuthor Commented:
Hello Saige,

It's working perfectly !!!!

Thanks a lot for your great help.

Edward
Edward van NijmweegenICT employeeAuthor Commented:
Hello Saige, hello all,

The above works great, but i have one small addition. In the above solution, there is only one option, but now i have more like:
"options": [
{
"key": "DOOR"
},
{
"key": "REFERENCE",
"input": "TEST JEROEN"
}
],

Open in new window


In the above solution one option is made with the following code:
     options = new[] { new { key = "DOOR" } },
                   

Open in new window


My question is, how can i make the orther(s). When i try this i get an error that my array is not correct. I tried something like:
   options = new object[] { 
                            new { key = "DOOR" }, 
                            new { key = "REFERENCE"}, 
                            new {input = dhlLabelRequest.orderReference.ToString() }

Open in new window


But this didn't work.

Thanks in advance.

Edward
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.