Link to home
Start Free TrialLog in
Avatar of kevinvw1
kevinvw1

asked on

C# HTTPWebRequest issue with JSON and POST

Hi I am using an api called HubSpot to update lead data on the HubSpot portal.
Here is the link to the Contact Update call -
http://developers.hubspot.com/docs/methods/contacts/update_contact
Here is the way you are supposed to POST -
https://api.hubapi.com/contacts/v1/contact/vid/61571/profile?hapikey=demo

and you pass JSON data like this -

{
  "properties": [
    {
      "property": "lifecyclestage",
      "value": "customer"
    }
  ]
}

I know the code works because if the JSON data is correctly formed everything updates fine and there are no errors
If the JSON data is not formed correctly I get an error 400  -
System.Net.WebException: The remote server returned an error: (400) Bad Request.
When this line is hit -
response = (HttpWebResponse)request.GetResponse();
the C# code immediately hits the "catch" block and my response variable is null -

However, if I If I process the same POST (with improperly formed JSON) using POSTMAN (a Google Chrome plugin), I get more information.  
I still get the error 400 Bad Request, but I actually see return JSON which gives more detail about the error.

{
    "status": "error",
    "message": "[{\"property\":\"Lifecyclestage\",\"msg\":\"Property \\\"Lifecyclestage\\\" does not exist\",\"error\":\"PROPERTY_DOESNT_EXIST\"}]",
    "requestId": "330ed575-902b-4d56-a9d9-2a63499cdaa3"
}

My question is how do I get this returned JSON data in my C# code since the response variable never gets set because it errors out.
ASKER CERTIFIED SOLUTION
Avatar of Craig Wagner
Craig Wagner
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of kevinvw1
kevinvw1

ASKER

Yes!  That was exactly the issue.  I know just enough about C# to be dangerous.  I didn't realize there were different exception classes for catch.

Thanks for teaching me something very valuable.