因此,我在這裏做的第一件事是將MultipartFormDataContent對象轉換爲Byte數組。
Byte [] byteArray = await form.ReadAsByteArrayAsync();
然後我把它傳遞給一個函數,它使得HttpWebRequest()。
private string HttpPostRequest(string url, MultipartFormDataContent formData, Byte[] form)
{
HttpWebRequest myHttpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
myHttpWebRequest.Method = "POST";
myHttpWebRequest.ContentType = formData.Headers.ContentType.ToString();
myHttpWebRequest.ContentLength = formData.Headers.ContentLength.Value;
myHttpWebRequest.ProtocolVersion = HttpVersion.Version10;
myHttpWebRequest.ServicePoint.ConnectionLimit = 24;
myHttpWebRequest.KeepAlive = false;
myHttpWebRequest.Timeout = System.Threading.Timeout.Infinite;
myHttpWebRequest.AllowWriteStreamBuffering = false;
System.Net.ServicePointManager.Expect100Continue = false;
Stream requestStream = myHttpWebRequest.GetRequestStream();
int i = 0;
attachAttempt:
try
{
requestStream.Write(form, 0, form.Length);
}
catch (IOException e)
{
if (i < 5)
{
i++;
goto attachAttempt;
}
DialogResult attachFail;
string attachFailMessage = e.Message.ToString() + " Please check your network and try again.";
string attachFailCaption = "Network error.";
MessageBoxButtons emailFailButtons = MessageBoxButtons.OK;
attachFail = MessageBox.Show(attachFailMessage, attachFailCaption, emailFailButtons, MessageBoxIcon.Error);
return "";
}
requestStream.Close();
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
Stream responseStream = myHttpWebResponse.GetResponseStream();
StreamReader myStreamReader = new StreamReader(responseStream, Encoding.Default);
string pageContent = myStreamReader.ReadToEnd();
myStreamReader.Close();
responseStream.Close();
myHttpWebResponse.Close();
return pageContent;
}
我在研究了與這個領域相關的幾個建議後編譯了這個。你可能會發現你可能不需要在myHttpWebRequest對象上設置一些標誌,但這對我來說是有效的。我還發現,網絡上的問題會嚴重影響這一點,因爲您的主機和目標機器之間的連接可能會中止,並且正因爲如此,我已將Write()放入try和catch塊以防萬一需要輸出一個錯誤。