/// <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;
}
?
?
?
?
?以上紅色部分就是解決亂碼的關(guān)鍵所在
本站僅提供存儲服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請
點擊舉報。