0

因此,对于我的家庭作业,我需要制作一个不会使用 SQL(如我以前那样),而是使用其余 api 的应用程序。问题是我从来没有这样做过,也不知道如何配置它。

到目前为止,我得到了这个:

string strUrlTest = String.Format("https://test.api.amadeus.com/v1/shopping/flight-offers");
WebRequest requestObjGet = WebRequest.Create(strUrlTest);

requestObjGet.Method = "GET";
requestObjGet.Headers.Add("API KEY", 
"API SECRET);

HttpWebResponse responseObjGet = null;
responseObjGet = (HttpWebResponse)requestObjGet.GetResponse();

string strResultTest = null;
using(Stream stream = responseObjGet.GetResponseStream())
{
    StreamReader sr = new StreamReader(stream);
    strResultTest = sr.ReadToEnd();
    sr.Close();
}

我只是想用调试器看看我是否得到了所有数据,但我的程序在

responseObjGet = (HttpWebResponse)requestObjGet.GetResponse();

你能帮我弄清楚吗?

4

2 回答 2

3

I wrote a code example in C#, replace apikey and apisecret by the ones you get on the portal by creating an application. You can find a guide here.

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;

namespace testApp
{
    public class AmadeusTest
    {
        static void Main()
        {
            const string URL = "https://test.api.amadeus.com/v1/shopping/flight-destinations?origin=BOS";
            string token = getToken();
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri(URL);
            client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "Bearer " + token);
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "");

            Task<HttpResponseMessage> response = client.SendAsync(request);
            string myJsonResponse = Newtonsoft.Json.JsonConvert.DeserializeObject(response.Result.Content.ReadAsStringAsync().Result).ToString();
            JObject jsonObject = JObject.Parse(myJsonResponse);

            Console.WriteLine(myJsonResponse);
            Console.WriteLine(jsonObject["data"][0]["destination"]);
            client.Dispose();
    }

    private static string getToken()
    {
        const string apikey = "";
        const string apisecret = "";
        const string tokenURL = "https://test.api.amadeus.com/v1/security/oauth2/token";

        string postData = $"grant_type=client_credentials&client_id={apikey}&client_secret={apisecret}";
        HttpClient client = new HttpClient();
        client.BaseAddress = new Uri(tokenURL);

        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "");
        request.Content = new StringContent(postData,
                                Encoding.UTF8,
                                "application/x-www-form-urlencoded");

        Task<HttpResponseMessage> response = client.SendAsync(request);
        if (response.Result.IsSuccessStatusCode)
        {
            string myJsonResponse = Newtonsoft.Json.JsonConvert.DeserializeObject(response.Result.Content.ReadAsStringAsync().Result).ToString();
            JObject jsonObject = JObject.Parse(myJsonResponse);
            client.Dispose();

            string token = (string)jsonObject["access_token"];
            return token;
        }
        else
        {
            Console.WriteLine("{0} ({1})", (int)response.Result.StatusCode, response.Result.ReasonPhrase);
            return response.Result.ReasonPhrase;
        }
      }
   }
}

The getToken method is in charge of doing the authorization process (as explained here).

This token is used in the API call (in the Main method). It is added to the Authorization header with the value: Bearer {token}

于 2019-06-10T07:55:43.577 回答
1

首先,您需要获取访问令牌,以检索数据。我是如何做到这一点的,你可以在下面的代码中看到。

[HttpGet("[action]")]
    public async Task<List<FlightOffersModel>> GetData(string origin, string destination, string departureDate, string returnDate, string adults, string currency)
    {

        const string client_id = "oqsIlG0xAbnlXXXXXXXXXXg7GdYwemI5";
        const string client_secret = "lAcXXXXXXXXX5AD0";
        string token = await GetToken(client_id, client_secret);

        const string baseUrl = "https://test.api.amadeus.com/v1/";
        string urlParams = "shopping/flight-offers?origin=" + origin + "&destination=" + destination + "&departureDate=" + departureDate;
        urlParams += returnDate == "" || returnDate == null ? "" : "&returnDate=" + returnDate;
        urlParams += "&adults=" + adults + "&nonStop=false&currency=" + currency + "&max=50";
        FlightOffer ff = null;
        List<FlightOffersModel> model = new List<FlightOffersModel>();

        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri(baseUrl);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.amadeus+json"));
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

            HttpResponseMessage response = await client.GetAsync(urlParams);
            if (response.IsSuccessStatusCode)
            {
                var x = await response.Content.ReadAsStringAsync();
                var xx = JObject.Parse(x);
                ff = JsonConvert.DeserializeObject<FlightOffer>(xx.ToString());

                foreach (var fo in ff.Data)
                {
                    FlightOffersModel temp = new FlightOffersModel();
                    foreach (var item in fo.OfferItems)
                    {
                        foreach (var service in item.Services)
                        {
                            if (item.Services.IndexOf(service) < 1)
                            {
                                temp.BrojPresjedanjaPovratak = item.Services.Length > 1 ? GetBrojPresjedanja(item.Services[1]) : 0;
                                temp.BrojPresjedanjaOdlazak = GetBrojPresjedanja(item.Services[0]);
                                temp.BrojPutnika = GetBrojPutnika(service.Segments);
                                temp.UkupnaCijena = item.Price.Total;
                                temp.Valuta = ff.Meta.Currency;
                                temp.PolazniAerodrom = GetAerodromName(service.Segments, "departure", ff.Dictionaries.Locations);
                                temp.OdredisniAerodrom = GetAerodromName(service.Segments, "arrival", ff.Dictionaries.Locations);
                                temp.DatumPolaska = GetDatumLeta(service.Segments, "departure");
                                temp.DatumPovratka = GetDatumLeta(service.Segments, "arrival");

                                model.Add(temp);
                            }
                        }
                    }
                }
            }
        }
        return model;
    }

这部分代码是获取访问令牌

const string client_id = "oqsIlG0xAbnlXXXXXXXXXXg7GdYwemI5";
    const string client_secret = "lAcXXXXXXXXX5AD0";
    string token = await GetToken(client_id, client_secret);

这是 GetToken 函数:

private async Task<string> GetToken(string client_id, string client_secret)
    {
        AccessToken s = null;
        using (var httpClient = new HttpClient())
        {
            using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://test.api.amadeus.com/v1/security/oauth2/token"))
            {
                request.Content = new StringContent("grant_type=client_credentials&client_id=" + client_id + "&client_secret=" + client_secret, Encoding.UTF8, "application/x-www-form-urlencoded");

                HttpResponseMessage response = await httpClient.SendAsync(request);

                if (response.IsSuccessStatusCode)
                {
                    s = await response.Content.ReadAsAsync<AccessToken>();
                }
            }
        }

        return s.Access_token;
    }

其余代码根据用户输入的参数提供数据。

于 2019-06-26T19:13:32.737 回答