/// <summary> /// post请求这个正常使用 /// </summary> /// <param name="URL"></param> /// <param name="postdata"></param> /// <returns></returns> public static string HttpPost4(string URL, string postdata) { // Create a request using a URL that can receive a post. HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL); // Set the Method property of the request to POST. request.Method = "POST"; // Create POST data and convert it to a byte array. string postData = postdata;//"This is a test that posts this string to a Web server."; byte[] byteArray = Encoding.UTF8.GetBytes(postData); // Set the ContentType property of the WebRequest. request.ContentType = "application/x-www-form-urlencoded"; // Set the ContentLength property of the WebRequest. request.ContentLength = byteArray.Length; // Get the request stream. Stream dataStream = request.GetRequestStream(); // Write the data to the request stream. dataStream.Write(byteArray, 0, byteArray.Length); // Close the Stream object. dataStream.Close(); // Get the response. HttpWebResponse response = (HttpWebResponse)request.GetResponse(); // Display the status. Console.WriteLine(((HttpWebResponse)response).StatusDescription); // Get the stream containing content returned by the server. dataStream = response.GetResponseStream(); var ce = response.ContentEncoding; if(ce.ToLower()=="gzip"){//判断解决乱码 dataStream = new GZipStream(dataStream,CompressionMode.Decompress); } var encoding = response.CharacterSet;//判断解决乱码 StreamReader reader = null; switch (encoding) { case "utf-8": reader = new StreamReader(dataStream, Encoding.UTF8); break; case"gb2312": reader = new StreamReader(dataStream, Encoding.GetEncoding("gb2312")); break; default: reader = new StreamReader(dataStream, Encoding.Default); break; } // Open the stream using a StreamReader for easy access. // StreamReader reader = new StreamReader(dataStream, Encoding.GetEncoding("utf-8"));//加上System.Text.Encoding.UTF8解决乱码 // Read the content. string responseFromServer = reader.ReadToEnd(); // Display the content. //Console.WriteLine(responseFromServer); // Clean up the streams. reader.Close(); dataStream.Close(); response.Close(); return responseFromServer; } 以上红色部分就是解决乱码的关键所在 |
|