1

我正在使用在此处找到的一些代码将图像发布到服务器。问题是我没有收到我应该收到的 Json 响应,而是在我的“ResponseReady”回调中收到 OL'SERVER NOT FOUND 响应。(编辑:原来这只是我的参数,这段代码工作得很好。)

这是我用来制作 POST 的课程

    public class PostSubmitter
    {

       public string url { get; set; }
       public Dictionary<string, object> parameters { get; set; }
       string boundary = "----------" + DateTime.Now.Ticks.ToString();
       HttpWebRequest webRequest;

       public void Submit()
       {
           // Prepare web request...
           webRequest = WebRequest.CreateHttp(url);
           webRequest.Method = "POST";
           webRequest.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);
           webRequest.BeginGetRequestStream(new AsyncCallback(RequestReady), webRequest);

       }

       private void RequestReady(IAsyncResult asynchronousResult)
       {
           using (Stream postStream = webRequest.EndGetRequestStream(asynchronousResult))
           {
                writeMultipartObject(postStream, parameters);
           }

           webRequest.BeginGetResponse(new AsyncCallback(ResponseReady), webRequest);

       }

       private void ResponseReady(IAsyncResult asynchronousResult)
       {
           try
           {
               using (var response =
                (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult))
               using (var streamResponse = response.GetResponseStream())
               using (var streamRead = new StreamReader(streamResponse))
               {
                   var responseString = streamRead.ReadToEnd();
                   var success = response.StatusCode == HttpStatusCode.OK;

                   if (responseString != null)
                   {
                       //JObject comes from Newtonsoft.Json ddl. This is a good one if your working with json
                       JObject jsonResponse = JObject.Parse(responseString);
                       //Do stuff with json.....
                   }
               }
           }
           catch (Exception e)
           {
               if (e.Message == "The remote server returned an error: NotFound.")
               {
                   webRequest.Abort();
                   Deployment.Current.Dispatcher.BeginInvoke(delegate() { MessageBox.Show("Unable to connect to server at this time, please try again later"); });
               }
               else
                   Deployment.Current.Dispatcher.BeginInvoke(delegate() { MessageBox.Show("Unable to upload photo at this time, please try again later"); });
               return;
           }
       }


       public void writeMultipartObject(Stream stream, object data)
       {
           using (StreamWriter writer = new StreamWriter(stream))
           {
               if (data != null)
               {
                   foreach (var entry in data as Dictionary<string, object>)
                   {
                       WriteEntry(writer, entry.Key, entry.Value);
                   }
               }
               writer.Write("--");
               writer.Write(boundary);
               writer.WriteLine("--");
               writer.Flush();
           }
       }

       private void WriteEntry(StreamWriter writer, string key, object value)
       {
           if (value != null)
           {
               writer.Write("--");
               writer.WriteLine(boundary);
               if (value is byte[])
               {
                   byte[] ba = value as byte[];

                   writer.WriteLine(@"Content-Disposition: form-data; name=""{0}""; filename=""{1}""", key, "sentPhoto.jpg");
                   writer.WriteLine(@"Content-Type: application/octet-stream");
                   writer.WriteLine(@"Content-Type: image / jpeg");
                   writer.WriteLine(@"Content-Length: " + ba.Length);
                   writer.WriteLine();
                   writer.Flush();
                   Stream output = writer.BaseStream;

                   output.Write(ba, 0, ba.Length);
                   output.Flush();
                   writer.WriteLine();
               }
               else
               {
                   writer.WriteLine(@"Content-Disposition: form-data; name=""{0}""", key);
                   writer.WriteLine();
                   writer.WriteLine(value.ToString());
               }
           }
       }
    }

使用这个类,我们可以使用以下代码行对服务器进行简单的 POST:

    Dictionary<string, object> postData = new Dictionary<string, object>()
                                                {
                                                    {"file", byteArrayOfImage}
                                                    //You can add other parameters here
                                                };
    PostSubmitter postToServer = new PostSubmitter() { url = getPicturePostUrl(), parameters = postData };
    postToServer.Submit();

这方面有很多问题......你会认为它们会让复杂的网络请求变得更容易......

提前感谢您的有用评论或随时提出问题。

4

1 回答 1

1

那么这段代码实际上工作得很好。我只是没有所需的参数之一,因此服务器拒绝了请求。

于 2012-07-11T21:38:15.640 回答