Link to home
Start Free TrialLog in
Avatar of lankapala
lankapala

asked on

C# Rest API

Hi,

This what vendor provided to test

Error is :

The remote server returned an error: (401) Unauthorized.

My code

string result = string.Empty;
            try
            {
                // Create Request
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(@"https://api.verilocation.com/public/v1/drivers?id=1093609330685010");
                req.Method = "GET";
                // Create Client
                WebClient client = new WebClient();
                req.ContentType ="application/json; charset=utf-8";
               // req.UseDefaultCredentials = true;
               // req.PreAuthenticate = true;
               // req.Credentials = CredentialCache.DefaultCredentials;

                //req.ContentLength=61;


                req.Credentials = new NetworkCredential("xxx", "xxx111");
               
                   req.Headers.Add("Authorization","Bearer  Y2xpdmUuaG9sZGVuQHN0b25laGFyZHkuY28udWs6bDBnMTV0MWM1");
             //   req.Headers.Add("Authorization","Basic Y2xpdmUuaG9sZGVuQHN0b25laGFyZHkuY28udWs6bDBnMTV0MWM1");
                req.ProtocolVersion =HttpVersion.Version11;
            
                WebResponse response = req.GetResponse();
                string responseData = new StreamReader(response.GetResponseStream()).ReadToEnd();
                MessageBox.Show(responseData.ToString());




              // Assign Credentials
               
                
            }
            catch (WebException ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }

Open in new window



Response Class (Status 200)
ModelExample Value


GET /public/v1/drivers/{id}

{
  "Id": 0,
  "Name": "string",
  "Mobile": "string",
  "Status": 0,
  "Username": "string",
  "Password": "string",
  "Email": "string",
  "ButtonId": "string"
}



curl -X GET --header 'Accept: application/json' --header 'Authorization: Basic Y2xpdmUuaG9sZGVuQHN0b25laGFyZHkuY28udWs6bDBnMTV0MWM1' 'https://api.verilocation.com/public/v1/drivers/0'
Request URL
https://api.verilocation.com/public/v1/drivers/0
Response Body
{
  "Message": "Authorization has been denied for this request."
}
Response Code
401
Response Headers
{
  "date": "Wed, 01 Nov 2017 00:11:10 GMT",
  "www-authenticate": "Bearer",
  "server": "Microsoft-IIS/8.5",
  "x-aspnet-version": "4.0.30319",
  "x-powered-by": "ASP.NET",
  "access-control-allow-methods": "GET, POST, PUT, DELETE, OPTIONS",
  "content-type": "application/json; charset=utf-8",
  "access-control-allow-origin": "*",
  "cache-control": "no-cache",
  "access-control-allow-headers": "Authorization,Content-Type,X-Requested-With, Accept",
  "content-length": "61"
}
Avatar of Miguel Oz
Miguel Oz
Flag of Australia image

401 UNAUTHORIZED
The request has not been applied because it lacks valid authentication credentials for the target resource.
Basically your credentials are not authorised to use the API. I will contact vendor for the correct username/ password and header Authorization that you should use for your case. If the the credentials are correct then they need to check user permissions to all your required functionality
Are you using a proxy?
Avatar of lankapala
lankapala

ASKER

No
Have you contacted the vendor as suggested in my first comment?
yes,they said
"Looks like that username and password is working fine from our end:
I can only surmise the API isn’t being called correctly."
Contact them again and send your code and the error details. 401 is a permission issue. Nothing to do with call unless you are not authorised to call this particular API feature. Ask them to run your code and whether they have OK response, Make sure they tell you which VS/.net framework version they are using as well just in case.
As they said, I change my coding,then no error message,Bu when i add records no error message,
Bu i can get all the details form the code, How to check the i have adding wwrites, when i trying to add nor error messages
Please post post the vendor original code to compare with your existing code. Also include the documentation on how to use their API.
Vendor Code
public async Task<Jobs> CreateJob(int vehicleId, double latitude, double longitude, string destinationAddress
             , string destinationDescription, string destinationName, string message,int jobnumber
             
             
             
             )
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = this.baseUri;
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
                    "Bearer",
                    this.userObject.access_token);

                var job = new Jobs
                {
                    
                    DestinationAddress = destinationAddress,
                    DestinationDescription = destinationDescription,
                    DestinationName = destinationName,
                    VehicleId = vehicleId,
                    DestinationLatitude = latitude,
                    DestinationLongitude = longitude,
                    Message = message,
                    Id = jobnumber
                };

                var content = new JavaScriptSerializer().Serialize(job);
                
                var response = await client.PostAsync(
                                   String.Format("/public/{0}/jobs",Version) ,
                                   new StringContent(content, Encoding.UTF8, "application/json"));

                var responseContent = await response.Content.ReadAsStringAsync();

                var id = 0;
                if ((response.StatusCode != HttpStatusCode.OK) ||
                    (responseContent == null) ||
                    (!int.TryParse(responseContent, out id)))
                {
                    return job;
                }

                job.Id = id;
                return job;
            }
        }

Open in new window


Calling
 try
            {
            string DestinationAddress = txtDestinationAddress.Text.ToString();
            string DestinationDescription = txtDestinationAddress.Text.ToString();
            double DestinationLatitude =Convert.ToDouble( txtLt.Text.ToString());
            double DestinationLongitude = Convert.ToDouble(txtLong.Text.ToString());
            string DestinationName = txtdetname.Text.ToString();
            string Message = txtMsg.Text.ToString();
            int jobNumber =Convert.ToInt32( txtJobNumber.Text.ToString());
            var c = new Client();
           c.SetCredentials("tttt", "ascc");
            
            Task.Run(
              async () =>
              {
//int vehicleId, double latitude, double longitude, string destinationAddress
           //  , string destinationDescription, string destinationName, string message,int jobnumber
                  
                  await c.Login();
                  var job = await c.CreateJob(Convert.ToInt32(txtvehicleid.Text.ToString()), DestinationLatitude, DestinationLongitude, DestinationAddress, DestinationDescription, DestinationName, Message, jobNumber);
                  MessageBox.Show("Added"+String.Format("Vehicle ID {0},Message{1},Job Number {2}" ,job.VehicleId,job.Message,job.Id));
                  
   }
          ).GetAwaiter().GetResult();


            }
            catch (WebException ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Miguel Oz
Miguel Oz
Flag of Australia 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
Hi Miguel Oz, I need to accept your answer but there is no button
thx