HttpWebRequest在HttpWebRequest.GetRequestStream()超时

时间:2016-06-03 03:42:06

标签: c# httpwebrequest httpwebresponse

我花了好几个小时试图找出这个问题,并按照类似问题的解决方案,但到目前为止没有任何工作。因为我已经没有使用的解决方案了,所以我开始感到沮丧。

我试图通过HttpWebRequest将文件上传到服务器。连接每次都在HttpWebRequest.GetRequestStream()超时。在这里阅读问题,我已经看到这是连接没有妥善处理的问题。我认为我正确地关闭了连接,并且我的reposnse流也被封装在using块中,正如许多人在此建议的那样。

这是我的代码:

HttpWebRequest requestToServer = (HttpWebRequest)WebRequest.Create(url);

// Define a boundary string
string boundaryString = "----";

// Turn off the buffering of data to be written, to prevent
// OutOfMemoryException when sending data
requestToServer.AllowWriteStreamBuffering = false;
// Specify that request is a HTTP post
requestToServer.Method = WebRequestMethods.Http.Post;
// Specify that the content type is a multipart request
requestToServer.ContentType
    = "multipart/form-data; boundary=" + boundaryString;
// Turn off keep alive
requestToServer.KeepAlive = false;


ASCIIEncoding ascii = new ASCIIEncoding();
string boundaryStringLine = "\r\n--" + boundaryString + "\r\n";
byte[] boundaryStringLineBytes = ascii.GetBytes(boundaryStringLine);

string lastBoundaryStringLine = "\r\n--" + boundaryString + "--\r\n";
byte[] lastBoundaryStringLineBytes = ascii.GetBytes(lastBoundaryStringLine);


string fileUrl = file;
// Get the byte array of the string part of the myFile content
// disposition
string myFileContentDisposition = string.Format(
    "Content-Disposition: form-data;name=\"{0}\"; "
     + "filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n",
    "myFile", Path.GetFileName(fileUrl), Path.GetExtension(fileUrl));
byte[] myFileContentDispositionBytes =
    ascii.GetBytes(myFileContentDisposition);

var name = Path.GetFileName(fileUrl);

FileInfo fileInfo = new FileInfo(fileUrl);

// Calculate the total size of the HTTP request
long totalRequestBodySize = boundaryStringLineBytes.Length * 2
    + lastBoundaryStringLineBytes.Length
    + myFileContentDispositionBytes.Length
    + fileInfo.Length;
// And indicate the value as the HTTP request content length
requestToServer.ContentLength = totalRequestBodySize;


// Write the http request body directly to the server
using (Stream s = requestToServer.GetRequestStream())
{

    // Send the file content disposition over to the server
    s.Write(boundaryStringLineBytes, 0, boundaryStringLineBytes.Length);
    s.Write(myFileContentDispositionBytes, 0,
        myFileContentDispositionBytes.Length);

    // Send the file binaries over to the server, in 1024 bytes chunk
    FileStream fileStream = new FileStream(fileUrl, FileMode.Open,
        FileAccess.Read);
    byte[] buffer = new byte[1024];
    int bytesRead = 0;
    while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
    {
        s.Write(buffer, 0, bytesRead);
    } // end while

    fileStream.Close();

    // Send the last part of the HTTP request body
    s.Write(lastBoundaryStringLineBytes, 0, lastBoundaryStringLineBytes.Length);

    string responseString = "";
    WebResponse response = requestToServer.GetResponse();

    using (Stream responseStream = response.GetResponseStream())
    {
        using (StreamReader responseReader = new System.IO.StreamReader(responseStream, Encoding.UTF8))
        {
            responseString = responseReader.ReadToEnd();
            return responseString;
        }
    }
}

超时发生在using (Stream s = requestToServer.GetRequestStream())。一切都运转良好,但现在却没有。如果有人能弄清楚我的代码有什么问题,我将不胜感激。

谢谢!

修改

这里是完整的堆栈跟踪:

System.Net.WebException: Error: ConnectFailure (Connection timed out)

06-03 09:15:41.521 D/Mono    ( 3839): DllImport attempting to load: '/system/lib/liblog.so'.
06-03 09:15:41.521 D/Mono    ( 3839): DllImport loaded library '/system/lib/liblog.so'.
06-03 09:15:41.522 D/Mono    ( 3839): DllImport searching in: '/system/lib/liblog.so' ('/system/lib/liblog.so').
06-03 09:15:41.523 D/Mono    ( 3839): Searching for '__android_log_print'.
06-03 09:15:41.523 D/Mono    ( 3839): Probing '__android_log_print'.
06-03 09:15:41.524 D/Mono    ( 3839): Found as '__android_log_print'.
06-03 09:15:41.536 I/MonoDroid( 3839): UNHANDLED EXCEPTION:
06-03 09:15:41.537 I/MonoDroid( 3839): System.Net.WebException: Error: ConnectFailure (Connection timed out) ---> System.Net.Sockets.SocketException: Connection timed out
06-03 09:15:41.538 I/MonoDroid( 3839):   at System.Net.Sockets.Socket.Connect (System.Net.EndPoint remoteEP) [0x000c2] in <filename unknown>:0 
06-03 09:15:41.538 I/MonoDroid( 3839):   at System.Net.WebConnection.Connect (System.Net.HttpWebRequest request) [0x0019b] in <filename unknown>:0 
06-03 09:15:41.538 I/MonoDroid( 3839):   --- End of inner exception stack trace ---
06-03 09:15:41.538 I/MonoDroid( 3839):   at System.Net.HttpWebRequest.EndGetRequestStream (IAsyncResult asyncResult) [0x00043] in <filename unknown>:0 
06-03 09:15:41.538 I/MonoDroid( 3839):   at System.Net.HttpWebRequest.GetRequestStream () [0x00057] in <filename unknown>:0 
06-03 09:15:41.538 I/MonoDroid( 3839):   at chunkedUpload.UploadFile.upload (System.String file, System.String url) [0x000e6] in c:\Users\Ahmed\Documents\Visual Studio 2013\Projects\chunkedUpload\chunkedUpload\UploadFile.cs:115 
06-03 09:15:41.538 I/MonoDroid( 3839):   at chunkedUpload.MainActivity+<button_Click>d__0.MoveNext () [0x0003d] in c:\Users\Ahmed\Documents\Visual Studio 2013\Projects\chunkedUpload\chunkedUpload\MainActivity.cs:57 
06-03 09:15:41.538 I/MonoDroid( 3839): --- End of stack trace from previous location where exception was thrown ---
06-03 09:15:41.538 I/MonoDroid( 3839):   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in <filename unknown>:0 
06-03 09:15:41.539 I/MonoDroid( 3839):   at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<ThrowAsync>m__0 (System.Object state) [0x00000] in <filename unknown>:0 
06-03 09:15:41.539 I/MonoDroid( 3839):   at Android.App.SyncContext+<Post>c__AnonStorey0.<>m__0 () [0x00000] in /Users/builder/data/lanes/3053/a94a03b5/source/monodroid/src/Mono.Android/src/Android.App/SyncContext.cs:18 
06-03 09:15:41.539 I/MonoDroid( 3839):   at Java.Lang.Thread+RunnableImplementor.Run () [0x0000b] in /Users/builder/data/lanes/3053/a94a03b5/source/monodroid/src/Mono.Android/src/Java.Lang/Thread.cs:36 
06-03 09:15:41.539 I/MonoDroid( 3839):   at Java.Lang.IRunnableInvoker.n_Run (IntPtr jnienv, IntPtr native__this) [0x00009] in /Users/builder/data/lanes/3053/a94a03b5/source/monodroid/src/Mono.Android/platforms/android-23/src/generated/Java.Lang.IRunnable.cs:71 
06-03 09:15:41.539 I/MonoDroid( 3839):   at (wrapper dynamic-method) System.Object:014507e3-fd28-45b0-b68f-cb466da601fa (intptr,intptr)
An unhandled exception occured.

06-03 09:15:43.243 E/mono    ( 3839): 
06-03 09:15:43.243 E/mono    ( 3839): Unhandled Exception:
06-03 09:15:43.243 E/mono    ( 3839): System.Net.WebException: Error: ConnectFailure (Connection timed out) ---> System.Net.Sockets.SocketException: Connection timed out
06-03 09:15:43.243 E/mono    ( 3839):   at System.Net.Sockets.Socket.Connect (System.Net.EndPoint remoteEP) [0x000c2] in <filename unknown>:0 
06-03 09:15:43.243 E/mono    ( 3839):   at System.Net.WebConnection.Connect (System.Net.HttpWebRequest request) [0x0019b] in <filename unknown>:0 
06-03 09:15:43.243 E/mono    ( 3839):   --- End of inner exception stack trace ---
06-03 09:15:43.243 E/mono    ( 3839):   at System.Net.HttpWebRequest.EndGetRequestStream (IAsyncResult asyncResult) [0x00043] in <filename unknown>:0 
06-03 09:15:43.243 E/mono    ( 3839):   at System.Net.HttpWebRequest.GetRequestStream () [0x00057] in <filename unknown>:0 
06-03 09:15:43.243 E/mono    ( 3839):   at chunkedUpload.UploadFile.upload (System.String file, System.String url) [0x000e6] in c:\Users\Ahmed\Documents\Visual Studio 2013\Projects\chunkedUpload\chunkedUpload\UploadFile.cs:115 
06-03 09:15:43.243 E/mono    ( 3839):   at chunkedUpload.MainActivity+<button_Click>d__0.MoveNext () [0x0003d] in c:\Users\Ahmed\Documents\Visual Studio 2013\Projects\chunkedUpload\chunkedUpload\MainActivity.cs:57 
06-03 09:15:43.243 E/mono    ( 3839): --- End of stack trace from previous location where exception was thrown ---
06-03 09:15:43.243 E/mono    ( 3839):   at (wrapper dynamic-method) System.Object:014507e3-fd28-45b0-b68f-cb466da601fa (intptr,intptr)
06-03 09:15:43.243 E/mono    ( 3839):   at (wrapper native-to-managed) System.Object:014507e3-fd28-45b0-b68f-cb466da601fa (intptr,intptr)
06-03 09:15:43.244 E/mono-rt ( 3839): [ERROR] FATAL UNHANDLED EXCEPTION: System.Net.WebException: Error: ConnectFailure (Connection timed out) ---> System.Net.Sockets.SocketException: Connection timed out
06-03 09:15:43.244 E/mono-rt ( 3839):   at System.Net.Sockets.Socket.Connect (System.Net.EndPoint remoteEP) [0x000c2] in <filename unknown>:0 
06-03 09:15:43.244 E/mono-rt ( 3839):   at System.Net.WebConnection.Connect (System.Net.HttpWebRequest request) [0x0019b] in <filename unknown>:0 
06-03 09:15:43.244 E/mono-rt ( 3839):   --- End of inner exception stack trace ---
06-03 09:15:43.244 E/mono-rt ( 3839):   at System.Net.HttpWebRequest.EndGetRequestStream (IAsyncResult asyncResult) [0x00043] in <filename unknown>:0 
06-03 09:15:43.244 E/mono-rt ( 3839):   at System.Net.HttpWebRequest.GetRequestStream () [0x00057] in <filename unknown>:0 
06-03 09:15:43.244 E/mono-rt ( 3839):   at chunkedUpload.UploadFile.upload (System.String file, System.String url) [0x000e6] in c:\Users\Ahmed\Documents\Visual Studio 2013\Projects\chunkedUpload\chunkedUpload\UploadFile.cs:115 
06-03 09:15:43.244 E/mono-rt ( 3839):   at chunkedUpload.MainActivity+<button_Click>d__0.MoveNext () [0x0003d] in c:\Users\Ahmed\Documents\Visual Studio 2013\Projects\chunkedUpload\chunkedUpload\MainActivity.cs:57 
06-03 09:15:43.244 E/mono-rt ( 3839): --- End of stack trace from previous location where exception was thrown ---
06-03 09:15:43.244 E/mono-rt ( 3839):   at (wrapper dynamic-method) System.Object:014507e3-fd28-45b0-b68f-cb466da601fa (intptr,intptr)
06-03 09:15:43.244 E/mono-rt ( 3839):   at (wrapper native-to-managed) System.Object:014507e3-fd28-45b0-b68f-cb466da601fa (intptr,intptr)

0 个答案:

没有答案