WP7上的POST请求

时间:2011-11-08 15:00:15

标签: silverlight windows-phone-7 httpwebrequest windows-phone-7.1

我已经死了大约6个小时试图找出如何在WP7中发出常规POST请求,我尝试了在这里和其他许多地方发布的类似问题的答案,我也尝试过很多不同的API POST请求,他们都会导致某个问题,

  

远程服务器返回错误:NotFound。

似乎每次都缺少某些东西。

所以,如果你有人请告诉我们如何正确地在这个WP7中获得POST请求

5 个答案:

答案 0 :(得分:5)

我用它来发布到Facebook没有任何问题:

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(requestUrl);
request.Method = "POST";
request.BeginGetResponse((e) =>
{
    try
    {
        WebResponse response = request.EndGetResponse(e);
        // Do Stuff
    }
    catch (WebException ex)
    {
        // Handle
    }
    catch (Exception ex)
    {
        // Handle
    }
}, null);

我假设您已经尝试了这一点,因此它可能与发布数据有关(在上面的示例中,因为Facebook使用查询字符串,所以不是这样)。你能给我们更多的信息吗?

编辑:这是一个用于编写帖子数据的(未经测试的)示例:

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(requestUrl);
request.Method = "POST";
request.BeginGetRequestStream((e) =>
{
    using (Stream stream = request.EndGetRequestStream(e))
    {
        // Write data to the request stream
    }
    request.BeginGetResponse((callback) =>
    {
        try
        {
            WebResponse response = request.EndGetResponse(callback);
            // Do Stuff
        }
        catch (WebException ex)
        {
            // Handle
        }
        catch (Exception ex)
        {
            // Handle
        }
    }, null);
}, null);

答案 1 :(得分:2)

我使用以下类来使用WP7发出POST请求:

public class PostMultiPartFormData
{
    private Dictionary<string, object> Parameters;
    private Encoding ENCODING = Encoding.UTF8;
    private string BOUNDARY = "-----------------------------wp7postrequest";
    public event EventHandler PostComplete;

    public void Post(string postbackURL,
        Dictionary<string, object> parameters)
    {
        Parameters = parameters;

        Uri url = null;
        url = new Uri(postbackURL);


        HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
        request.Method = "POST";

        request.ContentType = "multipart/form-data; boundary=" + BOUNDARY;
        request.BeginGetRequestStream(new AsyncCallback(SendStatusUpdate), request);
    }

    private void SendStatusUpdate(IAsyncResult ar)
    {
        HttpWebRequest request = (HttpWebRequest)ar.AsyncState;
        Stream stream = request.EndGetRequestStream(ar);

        byte[] byteArray = GetMultipartFormData(Parameters, BOUNDARY);

        stream.Write(byteArray, 0, byteArray.Length);
        stream.Close();
        stream.Dispose();

        request.BeginGetResponse(new AsyncCallback(StatusUpdateCompleted), request);
    }

    private byte[] GetMultipartFormData(Dictionary<string, object> postParameters, string boundary)
    {
        Stream formDataStream = new System.IO.MemoryStream();
        foreach (var param in postParameters)
        {
            if (param.Value is byte[])
            {
                byte[] fileData = param.Value as byte[];

                string header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}.jpg\";\r\nContent-Type: application/octet-stream\r\n\r\n", boundary, param.Key, param.Key);

                formDataStream.Write(ENCODING.GetBytes(header), 0, header.Length);

                formDataStream.Write(fileData, 0, fileData.Length);
            }
            else
            {
                string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}\r\n", boundary, param.Key, param.Value);
                byte[] b = ENCODING.GetBytes(postData);
                foreach (var item in b)
                {
                    formDataStream.WriteByte(item);
                }
            }
        }

        string footer = "\r\n--" + boundary + "--\r\n";
        byte[] footerbytes = ENCODING.GetBytes(footer);
        formDataStream.Write(footerbytes, 0, footerbytes.Length);

        formDataStream.Position = 0;
        byte[] formData = new byte[formDataStream.Length];
        formDataStream.Read(formData, 0, formData.Length);
        formDataStream.Flush();
        formDataStream.Close();
        return formData;
    }

    private void StatusUpdateCompleted(IAsyncResult ar)
    {
        if (PostComplete != null)
        {
            PostComplete(ar, null);
        }
    }
}

示例:

PostMultiPartFormData postRequest = new PostMultiPartFormData();

        postRequest.PostComplete += new EventHandler( (sender, e) => 
        {
            IAsyncResult ar = ((IAsyncResult)sender);

            using (WebResponse resp = ((HttpWebRequest)ar.AsyncState).EndGetResponse(ar))
            {

                using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
                {

                    string responseString = sr.ReadToEnd();

                    this.Dispatcher.BeginInvoke(() =>
                    {
                        textBlock.Text = responseString;
                    });
                }
            }
        });

        postRequest.Post("http://localhost:50624/SSLProxy.ashx", 
            new Dictionary<string, object>() { { "param1", "value1" } });

这应该有用...... 如果它不让我知道! : - )

答案 2 :(得分:1)

为了更方便地访问高级http功能,请查看以下http类:

http://mytoolkit.codeplex.com/wikipage?title=Http

它封装了GET,POST,FILES(使用路径或Stream对象)和GZIP(WP7不直接支持)请求。

答案 3 :(得分:0)

添加帖子数据只需调用BeginGetRequestStream方法(另外,BeginGetResponse移动到GetRequestStreamCallback)

request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);

void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
    HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
    // End the stream request operation
    Stream postStream = webRequest.EndGetRequestStream(asynchronousResult);

    // Create the post data
    string postData = "post data";
    byte[] byteArray = Encoding.Unicode.GetBytes(postData);

    // Add the post data to the web request            
    postStream.Write(byteArray, 0, byteArray.Length);
    postStream.Close();

    // Start the web request
    webRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), webRequest);
}

答案 4 :(得分:0)

我建议您使用postclient。这很简单。您只需要将dll文件的引用添加到项目中,然后编写如下内容:

public void authorize(string login, string password)
{
    Dictionary<string, object> parameters = new Dictionary<string, object>();
    parameters.Add("command", "login");
    parameters.Add("username", login);
    parameters.Add("password", password);

    PostClient proxy = new PostClient(parameters);
    proxy.DownloadStringCompleted += (sender, e) =>
    {
        if (e.Error == null)
        {
            MessageBox.Show(e.Result);
        }
    };
    proxy.DownloadStringAsync(new Uri("http://address.com/service", UriKind.Absolute));
}