locked
Conecting to web api RRS feed

  • Question

  • User1411016004 posted

    SO I'm trying to connect to a web API - according to their documentation:

     > Before you perform any operation, you first need to log in.
     > Send this HTTP request for login:
     > POST https://<Server Name/IP>:<port>/b1s/v1/Login
     {"CompanyDB": "US506", "UserName": "manager", "Password": "1234"}

     So, using the code from MS docs

    Dim request As WebRequest = WebRequest.Create("https://xxxxxxxx:port/b1s/v1/Login")
    request.Method = "POST"
    Dim postData As String = "{""CompanyDB"": ""XXXX"", ""UserName"": ""XXXX"", ""Password"": ""XXXX""}"
    Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
    request.ContentType = "application/json; charset=utf-8"
    request.ContentLength = byteArray.Length
    Dim dataStream As Stream = request.GetRequestStream()
    dataStream.Write(byteArray, 0, byteArray.Length)
    dataStream.Close()
    Dim response As WebResponse = request.GetResponse()
    Console.WriteLine(CType(response, HttpWebResponse).StatusDescription)
    dataStream = response.GetResponseStream()
    Dim reader As New StreamReader(dataStream)
    Dim responseFromServer As String = reader.ReadToEnd()
    Console.WriteLine(responseFromServer)
    reader.Close()
    dataStream.Close()
    response.Close()

     And all I get back is "The remote server returned an error: (400) Bad Request.". Why??

     I know a connection is possible, because I can connect using the Chrome extension Postman, using the same JSON data.

     ....

    Sunday, August 20, 2017 10:30 AM

All replies

  • User475983607 posted

     And all I get back is "The remote server returned an error: (400) Bad Request.". Why??

    It means the request is not formatted correctly.  Usually an indication that the post data is incorrect.  I generally prefer to fill an object then use the JSON formatter that comes with .NET to rather than hard code the format.

    https://docs.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/json-and-xml-serialization

    https://www.newtonsoft.com/json/help/html/SerializingJSON.htm

     I know a connection is possible, because I can connect using the Chrome extension Postman, using the same JSON data.

    Use a proxy tool like Fidder to capture the good request and compare it to you request that is not working to find the format error.

    Sunday, August 20, 2017 11:54 AM
  • User1411016004 posted

    HI

    Thanks for replying... I did try that, using the Newtonsoft.Json library, replacing

    Dim postData As String = "{""CompanyDB"": ""XXXX"", ""UserName"": ""XXXX"", ""Password"": ""XXXX""}" 

    with

     Dim cls As New clsX
     With cls
       .CompanyDB = "XXXX"
       .UserName = "XXXX"
       .Password = "XXXX"
     End With
     Dim postData As String = JsonConvert.SerializeObject(cls) 

    but still get the same error. I'll have a go with Fiddler and see if I can gleam anything from that...

    Sunday, August 20, 2017 12:35 PM
  • User1869050296 posted

    since you are already using postman, there is an inspect option which will show you the request/response sent and received similar to fiddler

    Monday, August 21, 2017 2:12 AM
  • User1168443798 posted

    Hi fredman,

    Could you capture the request by Fiddler?
    Per to the C# code, there is no need to convert postData from string to Byte, and I suggest you check below C# code, and implement the same code in VB.Net.

    var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://url");
    httpWebRequest.ContentType = "application/json";
    httpWebRequest.Method = "POST";
    
    using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
    {
        string json = "{\"user\":\"test\"," +
                      "\"password\":\"bla\"}";
    
        streamWriter.Write(json);
        streamWriter.Flush();
        streamWriter.Close();
    }
    
    var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
    {
        var result = streamReader.ReadToEnd();
    }

    If you failed to make it work, is there a test UserName and Password, then we could try to make a test to make a working demo.

    Best Regards,

    Edward

    Monday, August 21, 2017 6:57 AM
  • User1411016004 posted

    HI - thanks for that. I have in fact tried this exact code as well (perhaps you got it from the same Stackoverflow page I did! :) ) but again, I just get a "bad request" response. It's really quite odd. 

    I also tried using the class this guy wrote and put on GitHub (https://github.com/ademargomes/JsonRequest) and get slightly better results - but not usable: this time the error code is -1001 with message "Invalid session".  What's odd, is he uses the same code!

    I don't know....  I haven't got a test login I can share with you, yet, anyway. But I'll maybe have a go with Fiddler - I looked at it once before, and found it all a bit greek...

    Ta...

    Monday, August 21, 2017 8:19 AM
  • User1168443798 posted

    Hi fredman,

    I assume it is related with your web api. I made a test with below steps, and it works correctly.

    1. Create a web api which will accept Post data.

            [HttpPost]
            [Route("api/values/PostLogin")]
            public string PostLogin(CompanyLogin login)
            {
                return login.UserName;
            }
    
    
        public class CompanyLogin
        {
            public string CompanyDB { get; set; }
            public string UserName { get; set; }
            public string Password { get; set; }
        }
    

    2. Call web api from PostMan

    3. Call web api from VB.NET

    Best Regards,

    Edward

    Tuesday, August 22, 2017 2:57 AM