Python转C#:带身份验证的API Get请求实现(C#初学者求助)
Translating Authenticated Python GET Request to C#
Hey there! Since you already have Python experience, making this switch to C# should be straightforward once you get familiar with .NET's HttpClient and JSON handling. Here's a direct equivalent of your Python code, with explanations to map each part to what you know:
Required Namespaces
First, make sure you include these at the top of your C# file—they're the .NET equivalents of Python's requests and json modules:
using System; using System.Net.Http; using System.Net.Http.Headers; using System.Text.Json; using System.Threading.Tasks;
Full C# Code
This replicates your Python script's functionality, including basic authentication and JSON parsing:
class Program { static async Task Main(string[] args) { // Your credentials and API URL (matches your Python variables) string apiUser = "userexample@example.com"; string apiKey = "keyexample"; string url = "https://api.example.com/"; // Initialize HttpClient (reuse this instance instead of creating new ones!) using HttpClient client = new HttpClient(); // Add Basic Authentication header (equivalent to requests' auth=(user, key)) string credentials = $"{apiUser}:{apiKey}"; byte[] credentialsBytes = System.Text.Encoding.ASCII.GetBytes(credentials); string base64Credentials = Convert.ToBase64String(credentialsBytes); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", base64Credentials); try { // Send GET request (async/await is standard in C# for I/O operations) HttpResponseMessage response = await client.GetAsync(url); // Ensure the request succeeded (throws an error if status code is 4xx/5xx) response.EnsureSuccessStatusCode(); // Read and parse JSON response (equivalent to response.json()) string jsonContent = await response.Content.ReadAsStringAsync(); var jsonResponse = JsonSerializer.Deserialize<object>(jsonContent); // Print the parsed JSON in a readable format Console.WriteLine(JsonSerializer.Serialize(jsonResponse, new JsonSerializerOptions { WriteIndented = true })); } catch (HttpRequestException ex) { Console.WriteLine($"Request failed: {ex.Message}"); } } }
Key Mapping to Your Python Code
Let's break down how this matches what you wrote in Python:
requests.get(url, auth=(api_user, api_key))→client.GetAsync(url)with theAuthorizationheader set manually. C#'sHttpClientdoesn't have a directauthparameter, so we construct the Basic Auth header ourselves (this is exactly whatrequestsdoes under the hood).response.json()→JsonSerializer.Deserialize<object>(jsonContent). We first read the response content as a string, then deserialize it into a generic object. If you work with a specific JSON structure later, you can replaceobjectwith a custom class for better type safety.print(json_response)→ We serialize the parsed object back to a formatted string (theWriteIndented = trueoption makes it pretty-printed, just like Python's default JSON output).
Quick Notes
- Always reuse
HttpClientinstances instead of creating new ones each time—this avoids socket exhaustion issues in longer-running applications. - The
async/awaitpattern is standard in C# for asynchronous operations like HTTP requests (it keeps your app responsive while waiting for the API response). - If you're using an older .NET framework (pre-.NET Core 3.0), you might need to use
Newtonsoft.Json(Json.NET) instead ofSystem.Text.Json—just replace the deserialization line withJsonConvert.DeserializeObject(jsonContent).
内容的提问来源于stack exchange,提问作者Avery Delanfield
相关产品推荐
相关产品推荐

