postman除錯一個網頁鏈接的時候能除錯成功,它有一個自帶的header
Content-Type:multipart/form-data; boundary=<calculated when request is sent>
Content-Length:<calculated when request is sent>
然后我改用visual studio除錯的時候,怎么除錯都是失敗。
Content-Type寫application/x-www-form-urlencoded的時候會報500錯誤,寫text/html和multipart/form-data的時候也是一樣的失敗。
然后我試了一下把postman自帶的Content-Type取消,報了同樣的錯誤。所以推測出來是Content-Type的問題。
百度了一下multipart/form-data一定要一個boundary來分隔欄位。所以想請教一下怎么改這個欄位型別,還有原本的RequestData是string型別,怎么改能夠方便的加分隔符。
public static string UrlRequest(string UrlAddress, string RequestMethod, string RequestData = null)
{
GC.Collect();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(UrlAddress);
request.Method = RequestMethod;
CookieContainer cookie = new CookieContainer();
request.CookieContainer = cookie;
request.ContentType = "application/x-www-form-urlencoded";
if (RequestData != null)
{
//request.ContentLength = RequestData.Length;
Stream RequestStream = request.GetRequestStream();
byte[] bytes = Encoding.UTF8.GetBytes(RequestData);
RequestStream.Write(bytes, 0, bytes.Length);
RequestStream.Close();
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string encoding = response.ContentEncoding;
if (encoding == null || encoding.Length < 1)
{
encoding = "UTF-8";
}
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
string retString = reader.ReadToEnd();
request.Abort();
response.Close();
return retString;
}
uj5u.com熱心網友回復:
用WebClient.UploadFile試試https://docs.microsoft.com/zh-cn/dotnet/api/system.net.webclient.uploadfile?view=netframework-4.8
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/163815.html
標籤:C#
上一篇:socket高并發問題
