开发者

Windows phone 7: post some values, retrieve the response

How can I post a value to an online page, an开发者_如何学运维d then retrieve the response to put it in a string? It's a PHP page that take the $_POST value and then echo a response that I want to grab.


Look at the HttpWebRequest object.

public void DoWork()
{
    var url = "http://posttestserver.com/post.php";
    // Create the web request object
    HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
    webRequest.Method = "POST";
    webRequest.ContentType = "application/x-www-form-urlencoded";
    // Start the request
    webRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), webRequest);    
}
void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
    HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
    // End the stream request operation
    Stream postStream = webRequest.EndGetRequestStream(asynchronousResult);
    // Create the post data
    // Demo POST data 
    string postData = "Username=MyUserName&password=MyPassword";
    byte[] byteArray = Encoding.UTF8.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);
}

void GetResponseCallback(IAsyncResult asynchronousResult)
{
    try
    {
        HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
        HttpWebResponse response;
        // End the get response operation
        response = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult);
        Stream streamResponse = response.GetResponseStream();
        StreamReader streamReader = new StreamReader(streamResponse);
        var Response = streamReader.ReadToEnd();
        streamResponse.Close();
        streamReader.Close();
        response.Close();
    }
    catch (WebException e)
    {
        // Error treatment
        // ...
    }
}

private void button1_Click(object sender, RoutedEventArgs e)
{
    DoWork();
}

his code adapted slightly from this question

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜