Post request with parameters

gtrgtr Member Posts: 131
Hello,

I have a problem to send a post request with parameters - this is my code :
WebServiceURL := 'https://...';
Request := Request.Create(WebServiceURL);
Request.Method := 'POST';
Request.KeepAlive := TRUE;
Request.Timeout := 30000;
Request.Accept('application/json');
Request.ContentType('multipart/form-data');
postString := 'param1=123&param2=456';
Request.ContentLength := STRLEN(postString); 
StreamWriter := StreamWriter.StreamWriter(Request.GetRequestStream);
StreamWriter.Write(postString);
StreamWriter.Close;

I get a 500 error (see picture) so I don't know anything about why its rejected
But if there is something that seems to be wrong to you, please help !

Bye
«1

Answers

  • gtrgtr Member Posts: 131
    Picture I forgot to join :
  • RockWithNAVRockWithNAV Member Posts: 1,139
    Can it be in English Please??
    I believe its something like internal server error.
    Why there's no SOAP ACTION in the code??
  • gtrgtr Member Posts: 131
    Sorry - heres translation
    What do you mean my soap action
    I only want to send a request with parameters to a web server
  • RockWithNAVRockWithNAV Member Posts: 1,139
    Again its not in English I believe. :smile:

    I think you are trying to call a Webservice with some end point URL from NAV which is a SOAP Service, isnt it??
  • gtrgtr Member Posts: 131
    ah sorry for the translation - don't know if i can do better - will have a look this evening

    but the purpose is not call a soap service
    its about Groupon and POST /tracking_notification - if you want to have a look on their API description:
    https://scm.commerceinterface.com/api-doc/v2/#tracking_notification

    I had no problem to get the orders (GET) but I have problems to send data (POST)
  • gtrgtr Member Posts: 131
    edited 2017-01-19
    Hello and thanks for trying to help :smile:

    The first link does not help me because its not about how to handle httpwebrequest object (.net)
    I have already read the different articles of Gunnar about Json & NAV but sadly in the exemples he never shows the thing I need to do : Howto post parameters

    In the api help they give exemple for curl :
    curl -XPOST "https://scm.commerceinterface.com/api/v2/mark_exported" \
      -d"supplier_id=1" \
      -d"token=xYRPKcoakMoiRzWgKLV5TqPSdNAaZQT" \
      -d"ci_lineitem_ids=[54553919, 54553920]"
    

    So I need to know how is done in .net the part that adds the 3 parameters (supplier, token and ci_lineitem_ids)
  • zohaibu95@hotmail.comzohaibu95@hotmail.com Member Posts: 223
    You have to put the query string parameter in HttpContent which is a type of DotNet variable.
    Best Regards
    Zohaib Ahmed
    Dynamics NAV ERP Technical Consultant.

    please like / agree / verify my answer, if it was helpful for you. thanks.
  • gtrgtr Member Posts: 131
    I replaced Request.ContentType('multipart/form-data'); by Request.ContentType('application/json');
    And now I get 401 error

    Thanks for this hint, I tried with httpcontent but allways error 401
    I had a look on web but certainly I do not know how exactly to use this content type.
    Here's my new code :

    WebServiceURL := 'https://...';
    Request := Request.Create(WebServiceURL);
    Request.Method := 'POST';
    Request.KeepAlive := TRUE;
    Request.Timeout := 30000;
    Request.Accept('application/json');
    Request.ContentType('application/json');
    postString := 'param1=123&param2=456';
    HttpStringContent := HttpStringContent.StringContent(postString,Encoding.UTF8,'application/json');
    StreamWriter := StreamWriter.StreamWriter(Request.GetRequestStream);
    StreamWriter.Write(HttpStringContent);
    StreamWriter.Close;

    If you had a working exemple of sending a post request would be nice
  • zohaibu95@hotmail.comzohaibu95@hotmail.com Member Posts: 223
    401 means unauthorized user. Make sure you have valid user setup in NAV .
    Best Regards
    Zohaib Ahmed
    Dynamics NAV ERP Technical Consultant.

    please like / agree / verify my answer, if it was helpful for you. thanks.
  • gtrgtr Member Posts: 131
    401 is the response of groupon and I suppose that the supplier_id and token That I send as post parameters do not work correctly
    any comment on the code posted above and the way to prepare and add parameters would be helpfull
  • zohaibu95@hotmail.comzohaibu95@hotmail.com Member Posts: 223
    You can do POST request by using my this code:

    Parameters
    9donpyp2ot7d.png

    Local Variables
    5kakj16pwyb8.png

    CallRESTWebService(BaseUrl : Text;Method : Text;RestMethod : Text;VAR HttpContent : DotNet "System.Net.Http.HttpContent";VAR HttpResponseMessage : DotNet "System.Net.Http.HttpResponseMessage")
    
    HttpClient := HttpClient.HttpClient();
    HttpClient.BaseAddress := Uri.Uri(BaseUrl);
    
    CASE RestMethod OF
      'GET':    
        HttpResponseMessage := HttpClient.GetAsync(Method).Result;
      'POST':   
        HttpResponseMessage := HttpClient.PostAsync(Method,HttpContent).Result;
      'PUT':    
        HttpResponseMessage := HttpClient.PutAsync(Method,HttpContent).Result;
      'DELETE': 
        HttpResponseMessage := HttpClient.DeleteAsync(Method).Result;
    END;
    
    


    Explanation of the parameters

    BaseUrl – the first part of the url that is being called, e.g.: http://www.google.com/

    Method – the resource on the web service, in other words, the second part of the url, e.g. somecoolapi/parameter?option=value

    RestMethod – one of the request verbs, either GET, POST, PUT or DELETE

    HttpContent – the content to be sent with the POST or PUT command

    HttpResponseMessage – the response message containing the status code and the response body. This parameter is ByVar because the calling code needs to handle the specific response itself. That’s not part of the generic pattern.



    You have to put your data in HttpContent because you are using POST method. This is the correct way of sending parameters via post.

    Best Regards
    Zohaib Ahmed
    Dynamics NAV ERP Technical Consultant.

    please like / agree / verify my answer, if it was helpful for you. thanks.
  • gtrgtr Member Posts: 131
    OK I follow you as I already have seen this post on the net
    So I'm using postasync - but I do not know if this postrequest has been accepted by the target beause when I try to read the response I get this :
    <img src="https://us.v-cdn.net/5022383/uploads/FileUpload/ec/7898492df86a257032d80e1c755866.jpg&quot; /><img src="https://us.v-cdn.net/5022383/uploads/FileUpload/ec/7898492df86a257032d80e1c755866.jpg&quot; />

    The code I'm using :
    HttpStringContent := HttpStringContent.StringContent(postString,Encoding.UTF8,'application/json');
    HttpClient := HttpClient.HttpClient;
    responseMessage := HttpClient.PostAsync(WebServiceURL, HttpStringContent); 
    MESSAGE(FORMAT(responseMessage.ToString));
    

    How do I know that my request has been taken in account and that there was no error ?
    I'm not sure if I'm using the right way to get the answer of the target.
    Finally I should get something like this :
    Response:
    {
    "success": true
    }
  • gtrgtr Member Posts: 131
    And it seems that I do not have access to several methods and properties like :
    HttpResponseMessage.EnsureSuccessStatusCode()
    HttpResponseMessage.IsSuccessStatusCode
  • zohaibu95@hotmail.comzohaibu95@hotmail.com Member Posts: 223
    There is something wrong in initializing the variable. Can you please use the function which i have mentioned above? and please post the complete code so that i can test.

    Best Regards
    Zohaib Ahmed
    Dynamics NAV ERP Technical Consultant.

    please like / agree / verify my answer, if it was helpful for you. thanks.
  • ftorneroftornero Member Posts: 522
    gtr wrote: »
    Hello and thanks for trying to help :smile:

    The first link does not help me because its not about how to handle httpwebrequest object (.net)
    I have already read the different articles of Gunnar about Json & NAV but sadly in the exemples he never shows the thing I need to do : Howto post parameters

    In the api help they give exemple for curl :
    curl -XPOST "https://scm.commerceinterface.com/api/v2/mark_exported" \
      -d"supplier_id=1" \
      -d"token=xYRPKcoakMoiRzWgKLV5TqPSdNAaZQT" \
      -d"ci_lineitem_ids=[54553919, 54553920]"
    

    So I need to know how is done in .net the part that adds the 3 parameters (supplier, token and ci_lineitem_ids)

    If you take a look to the PHP example in the API documentation looks like you need to send a JSON structure with the data and your id information.

    req_data = {'supplier_id':'1',
    'token':'xYRPKcoakMoiRzWgKLV5TqPSdNAaZQT',
    'tracking_info':json.dumps([
    {"carrier": "UPS", "ci_lineitem_id": 54553918, "tracking": "123456"},
    {"quantity": 1, "carrier": "UPS", "ci_lineitem_id": 54553919, "tracking": "234567"}])}
     
    response = requests.post('https://scm.commerceinterface.com/api/v2/tracking_notification', data=req_data).json()


    Regards.
  • ftorneroftornero Member Posts: 522
    Sorry I said PHP example and it was Python.
  • gtrgtr Member Posts: 131
    Yes - I made some error on dotnet variable
    After correcting Code I get this code :
    LOCAL JsonSetOrdersExportedSend(postString : Text)
    BaseUrl := 'https://scm.commerceinterface.com/';
    //Method := 'api/v4/mark_exported';
    //postString := 'supplier_id=' + SupplierID + '&token=' + Token + '&ci_lineitem_ids=' + postString;
    Method := STRSUBSTNO('api/v4/mark_exported?supplier_id=%1&token=%2',SupplierID,Token);
    postString := 'ci_lineitem_ids=' + postString;
    HttpStringContent := HttpStringContent.StringContent(postString,Encoding.UTF8,'application/json');
    CallRESTWebService(
      BaseUrl, 
      Method, 
      'POST', 
      HttpStringContent, 
      HttpResponseMessage
    );
    result := HttpResponseMessage.Content.ReadAsStringAsync.Result;
    APIResult := JsonConvert.DeserializeObject(result,GETDOTNETTYPE(APIResult));
    MESSAGE(APIResult);
    
    LOCAL CallRESTWebService(BaseUrl : Text;Method : Text;RestMethod : Text;VAR HttpContent : DotNet "System.Net.Http.HttpContent";VAR HttpResponseMessage : DotNet "System.Net.Http.HttpResponseMessage")
    HttpClient := HttpClient.HttpClient();
    HttpClient.BaseAddress := Uri.Uri(BaseUrl);
    CASE RestMethod OF
      'GET':    
        HttpResponseMessage := HttpClient.GetAsync(Method).Result;
      'POST':   
        HttpResponseMessage := HttpClient.PostAsync(Method,HttpContent).Result;
      'PUT':    
        HttpResponseMessage := HttpClient.PutAsync(Method,HttpContent).Result;
      'DELETE': 
        HttpResponseMessage := HttpClient.DeleteAsync(Method).Result;
    END;
    HttpResponseMessage.EnsureSuccessStatusCode();  // Throws an error when no success
    

    I tried to make everything like in indicated in your previous message but there was one thing I did not found : What should be the type of APIResult ? As I don't know the answer I took text but so I can't get APIResult.Status

    Sadly, an error is thrown on HttpResponseMessage.EnsureSuccessStatusCode(); as shown in picture joint
    The problem is Authorization on Groupon site (401)
    As you see in commented code I tried to send supplier_id & token first in method and then in poststring
    Both are not working.
  • zohaibu95@hotmail.comzohaibu95@hotmail.com Member Posts: 223
    @gtr try removing/commenting the last line i.e.

    //HttpResponseMessage.EnsureSuccessStatusCode();

    and then check whether it is successful or not.
    Best Regards
    Zohaib Ahmed
    Dynamics NAV ERP Technical Consultant.

    please like / agree / verify my answer, if it was helpful for you. thanks.
  • gtrgtr Member Posts: 131
    edited 2017-01-20
    Ok here is the error message I get when commenting the last line
    And the content of result in the second picture
    I am sure of supplier_id and token as I get the orders from Groupon without any problem
  • zohaibu95@hotmail.comzohaibu95@hotmail.com Member Posts: 223
    First error is due to this line i guess

    APIResult := JsonConvert.DeserializeObject(result,GETDOTNETTYPE(APIResult));

    There is some issue in Deserializing the object.

    Second error is the supplier_id or token is missing.
    I guess u are missing the token because in case of POST web api we validate the user and we have the authentication_token i guess you are missing that.
    Best Regards
    Zohaib Ahmed
    Dynamics NAV ERP Technical Consultant.

    please like / agree / verify my answer, if it was helpful for you. thanks.
  • gtrgtr Member Posts: 131
    For APIResult as I said I suppose that it should not be of type text but what is the right type ?

    For the second error : sorry but I don't understand - can you suggest a solution ?
    With little hope I just tried to use credentials with httpclienthandler, and it does not work.
    Can't really see what is missing as I'm absolutely sure that supplierid and token have correct values as I watched them in debugger and compared them.
  • ftorneroftornero Member Posts: 522
    gtr wrote: »
    For APIResult as I said I suppose that it should not be of type text but what is the right type ?

    For the second error : sorry but I don't understand - can you suggest a solution ?
    With little hope I just tried to use credentials with httpclienthandler, and it does not work.
    Can't really see what is missing as I'm absolutely sure that supplierid and token have correct values as I watched them in debugger and compared them.

    The problem is that that is not the Method

    Method := STRSUBSTNO('api/v4/mark_exported?supplier_id=%1&token=%2',SupplierID,Token);

    doesn't work with "mark_exported" it works with "get_orders", check de documentation.

    With "mark_exported" the Method must be:

    Method := 'api/v4/mark_exported';

    And the suplier_id, token and real data must be send in as a JSON structure.

    Regards.




  • gtrgtr Member Posts: 131
    edited 2017-01-20
    Hello, I understand - ok for Method := 'api/v4/mark_exported';
    But then my problem is to understand what exactly I need to send to communicate supplier_id, token and real data.
    You say its in a Json structure.
    In documentation for php they say :
    $datatopost = array (
          "supplier_id" => "1",
          "token" => "xYRPKcoakMoiRzWgKLV5TqPSdNAaZQT",
          "ci_lineitem_ids" => json_encode ( array (54553919, 54553920) ),
       );
    
    I really am not sure about how to "translate" this in Json - perhaps something like this ?
    {"supplier_id": "1234", "token": "abcd", "ci_lineitem_ids": [123, 456]}

    {"supplier_id": "1234", "token": "abcd", "ci_lineitem_ids": ["123", "456"]} // edited
    This is what I just tried - and always the same 401 error // edited
    As any caracter counts, would it be possible to help me concerning usage of {, [, " and the whole Json structure ?
  • ftorneroftornero Member Posts: 522
    The Python example is more clear
    import requests #requires "requests" package
    import json
    response = requests.post('https://scm.commerceinterface.com/api/v4/mark_exported',
                           data={'supplier_id':'1', 'token':'xYRPKcoakMoiRzWgKLV5TqPSdNAaZQT',
                                 'ci_lineitem_ids':json.dumps([54553919, 54553920])}).json()
    if response['success'] == True:
       #Successfully marked as exported (only items which are not already marked exported)
       pass
    else:
       pass
    

    But looks like something how you are trying.

    Sorry I can help you more but I don't have the credentials to do any test with this API.

    Regards
  • gtrgtr Member Posts: 131
    edited 2017-01-22
    Hello again,
    Having not any idea whats not working, I just wanted to check if the request is sending postdatas correctly
    So I setup a testpage on my domain in which I write $_post data to a database table
    And as result I was surprised :
    The call with dotnet HTTPClient is not producing any postdata
    So I don't know what HTTPClient is doing but perhaps I'm missing a parameter ?

    Edit : I know that HTTClient is reaching my testpage because I write kind of IwasHERE in database when acceeding, just before $_post test
  • zaidtariqzaidtariq Member Posts: 52
    You may test using PostMan first. It will help you to know the correct parameters.
    Best Regards:
    Zaid Tariq
    Dynamics NAV/365 BC Developer at Dynamics 360

    please like / agree / verify my answer, if was helpful.
  • gtrgtr Member Posts: 131
    This is a nice tool
    And the result is clear - as soon as I specify supplier_id & token, I get a new result (missing parameters) and not 401

    So this confirms what I said in my last post - the target does not receive any postdata using HTTPclient as I use it
  • gtrgtr Member Posts: 131
    Postman was my saviour :smile:
    It was impossible for me to find any kind of Json formatted text which would allow me not to see the 401 error.
    But I tried x-www-form-urlencoded encoding and this was working on Postman and in my code too.
    Thanks to all of you.
  • zohaibu95@hotmail.comzohaibu95@hotmail.com Member Posts: 223
    edited 2017-01-23
    Great. You are welcome :)
    Best Regards
    Zohaib Ahmed
    Dynamics NAV ERP Technical Consultant.

    please like / agree / verify my answer, if it was helpful for you. thanks.
Sign In or Register to comment.