以下是一个使用WinForms和C#的示例代码,用于验证OpenAI API密钥的有效性:
using System; using System.Net; using System.Net.Http; using System.Threading.Tasks; using System.Windows.Forms; namespace OpenAI_Key_Validation { public partial class Form1 : Form { private const string API_KEY = "YOUR_API_KEY_HERE"; private const string API_URL = "https://api.openai.com/v1/engines/davinci-codex/completions"; public Form1() { InitializeComponent(); } private async void button1_Click(object sender, EventArgs e) { // Disable the button while the validation is in progress button1.Enabled = false; bool keyIsValid = await ValidateApiKeyAsync(); if (keyIsValid) { MessageBox.Show("API key is valid!"); } else { MessageBox.Show("Invalid API key."); } // Re-enable the button button1.Enabled = true; } private async Task<bool> ValidateApiKeyAsync() { using (var client = new HttpClient()) { // Set the API key in the Authorization header client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", API_KEY); // Send a test request to the OpenAI API to check if the key is valid try { var response = await client.PostAsync(API_URL, new StringContent("test")); if (response.StatusCode == HttpStatusCode.Unauthorized) { // The API key is invalid return false; } else if (response.IsSuccessStatusCode) { // The API key is valid return true; } else { // There was an error with the API request throw new Exception($"API request failed with status code {response.StatusCode}"); } } catch (HttpRequestException ex) { // There was an error with the HTTP request throw new Exception("HTTP request failed", ex); } } } } }
在代码中,将YOUR_API_KEY_HERE替换为您自己的OpenAI API密钥。然后,在窗体上添加一个按钮,并将其Click事件处理程序设置为button1_Click。当用户单击该按钮时,它将调用ValidateApiKeyAsync方法,该方法将尝试向OpenAI API发送一个测试请求来验证API密钥的有效性。如果API密钥有效,它将返回true,否则返回false。该方法使用HttpClient来进行HTTP请求,并使用Authorization标头将API密钥设置为Bearer令牌。
请注意,此代码仅在Windows操作系统上使用WinForms框架,如果您使用其他操作系统或UI框架,则可能需要进行适当的更改。