簡體   English   中英

使用HttpWebRequest和Json響應發布圖像-WP7

[英]POST an image using HttpWebRequest with Json response - WP7

我正在使用在這里找到的一些代碼來將映像發布到服務器。 問題是我沒有收到應有的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();

那里有很多問題……您可能會認為,這將使執行復雜的Web請求變得更加容易。

在此先感謝您提供的寶貴意見或隨時提出問題。

那么這段代碼實際上完美地工作了。 我只是沒有必需的參數之一,因此服務器拒絕了該請求。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM