简体   繁体   English

WP7上的POST请求

[英]POST Requests on WP7

I've been dying for about 6 hours trying to figure out how to make a regular POST request in WP7 , I tried the answers of similar questions posted here and on many other places, I also tried many different APIs POST request, they all lead to one certain problem, 我已经死了大约6个小时试图弄清楚如何在WP7中发出常规的POST请求,我尝试了在这里和其他许多地方发布的类似问题的答案,我也尝试过很多不同的API POST请求,他们都领先对某个问题,

The remote server returned an error: NotFound. 远程服务器返回错误:NotFound。

it seems like everytime there's something missing. 似乎每次都缺少一些东西。

So, if you please someone show us how to properly get a POST request right in this WP7 所以,如果你有人请告诉我们如何正确地在这个WP7中获得POST请求

I use this to post to facebook without any problem: 我用它来发布到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);

I assume you would have tried this already so it may be something to do with the post data (which isn't in the above example as facebook uses the query string). 我假设你已经尝试了这个,所以它可能与发布数据有关(在上面的例子中不是因为facebook使用了查询字符串)。 Can you give us any more info? 你能再告诉我们了吗?

EDIT: This is an (untested) example for writing post data: 编辑:这是一个用于编写帖子数据的(未经测试的)示例:

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);

I use the following class for making POST requests with WP7: 我使用以下类来使用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);
        }
    }
}

Example: 例:

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" } });

This should work... If it doesn't let me know! 这应该工作......如果它不让我知道! :-) :-)

For easier access to advanced http features check out these http classes: 为了更方便地访问高级http功能,请查看以下http类:

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

It encapsulates GET, POST, FILES (using path or Stream objects) and GZIP (not directly supported by WP7) requests. 它封装了GET,POST,FILES(使用路径或Stream对象)和GZIP(WP7不直接支持)请求。

I recommend you to use the postclient . 我建议你使用postclient It is pretty simple. 这很简单。 You just need to add reference to dll file into your project, and then write something like: 您只需要将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));
}

To add post data just call BeginGetRequestStream method (also, BeginGetResponse move to GetRequestStreamCallback) 要添加帖子数据,只需调用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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM