Question:
I encountered problems when I used the following code to execute the post request. There seems to be a mistake in the Catch block, I can't find it. Can you help me eliminate the fault?
Answer:
<code class="language-csharp">using System; using System.IO; using System.Net; using System.Text; class Class1 { private const string URL = "https://sub.domain.com/objects.json?api_key=123"; private const string DATA = @"{""object"":{""name"":""Name""}}"; static void Main(string[] args) { Class1.CreateObject(); } private static void CreateObject() { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL); request.Method = "POST"; request.ContentType = "application/json"; request.ContentLength = DATA.Length; StreamWriter requestWriter = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII); requestWriter.Write(DATA); requestWriter.Close(); try { WebResponse webResponse = request.GetResponse(); Stream webStream = webResponse.GetResponseStream(); StreamReader responseReader = new StreamReader(webStream); string response = responseReader.ReadToEnd(); Console.Out.WriteLine(response); responseReader.Close(); } catch (Exception e) { Console.Out.WriteLine("-----------------"); Console.Out.WriteLine(e.Message); } } }</code>
Although the code provided is effectively sent with POST request, it does not properly handle potential abnormalities. To solve this problem, please use the class, which specifically manages abnormalities related to Web requests. Here are the updated version of the code:
By using the class, you can capture and process any abnormalities that may occur during the web request, thereby providing more specific and more information error messages. The improved code also contains a check of, which can obtain more detailed error information from the server. Use the statement to ensure the correct shutdown and avoid the leakage of resources. WebException
The above is the detailed content of How to Properly Handle Exceptions When Making POST Requests in C#?. For more information, please follow other related articles on the PHP Chinese website!