HttpWebRequest调用WebRequest.Create报Invalid URI格式错误,求协助
Hey there! That error is popping up because the string "REPLACE_ME" you're passing to WebRequest.Create() isn't a valid Uniform Resource Identifier (URI) — the system has no idea how to parse it into a usable address. Let's break down how to fix this:
Common Fixes & Examples
Replace with a fully qualified, valid URI
You need to provide a complete URI that includes the protocol (likehttp://orhttps://), domain, and any path/query parameters your request needs. For example:var request = (HttpWebRequest)WebRequest.Create("https://example.com/api/endpoint");Without the protocol prefix, the .NET runtime can't distinguish between a web address, file path, or other type of resource.
Validate URI format before using it
If you're pulling the URI from a variable or user input, useUri.TryCreate()to check validity first and avoid exceptions:string targetUri = "your-actual-uri-here"; if (Uri.TryCreate(targetUri, UriKind.Absolute, out Uri validUri)) { var request = (HttpWebRequest)WebRequest.Create(validUri); // Proceed with your request logic } else { // Handle invalid URI case (show error, log, etc.) Console.WriteLine("Invalid URI format. Please check the address."); }Escape special characters if needed
If your URI includes spaces, ampersands, or other special characters, useUri.EscapeUriString()to encode them properly:string rawUri = "https://example.com/api/data?param=hello world"; string encodedUri = Uri.EscapeUriString(rawUri); var request = (HttpWebRequest)WebRequest.Create(encodedUri);
内容的提问来源于stack exchange,提问作者user1250264

