将参数添加到HttpWebRequest

时间:2014-04-15 22:45:47

标签: c# windows-phone-8

这个问题已被问了一百万次,但是没有一个回复对我有用。我最兴奋的是Http Post for Windows Phone 8但是因为它需要委托,所以我的代码不正确...从存储库调用Postdata函数,直接从这个函数得到响应会很好! / p>

如何将帖子参数添加到此代码中?我一直试图让它工作10个小时。

// Repository code

string url = "/bla/bla/" + blaId + "/";
Dictionary<string, string> postParams = new Dictionary<string, string>();
postParams.Add("value", message);
string response = await BlaDataContext.PostData(url, postParams);

// ...

public static async Task<string> PostData(string url, Dictionary<String, String> postParams)
{
    HttpWebRequest request = WebRequest.CreateHttp(APIURL + url);
    request.ContentType = "application/x-www-form-urlencoded";
    request.Method = "POST";
    postParams.Add("oauth_token", Contract.AccessToken); // where do I add this to the request??

    try
    {
        HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync();

        Debug.WriteLine(response.ContentType);
        Stream responseStream = response.GetResponseStream();
        string data;
        using (var reader = new StreamReader(responseStream))
        {
            data = reader.ReadToEnd();
        }
        responseStream.Close();

        return data;
    }
    catch (Exception e)
    {
        // whatever
    }
}

2 个答案:

答案 0 :(得分:0)

您需要将参数写入请求正文。

你可以使用像这样的扩展方法:

public static void AddFormData(this HttpWebRequest request, IDictionary<string, string> data)
{
    using (var memStream = new MemoryStream())
    using (var writer = new StreamWriter(memStream))
    {
        bool first = true;
        foreach (var d in data)
        {
            if (!first)
                writer.Append("&");
            writer.Write(Uri.EscapeDataString(d.Key));
            writer.Write("=");
            writer.Write(Uri.EscapeDataString(d.Value));
            first = false;
        }
        writer.Flush();
        request.ContentLength = memStream.Length;
        memStream.Position = 0;
        using (var reqStream = request.GetRequestStream())
        {
            memStream.CopyTo(reqStream);
        }
    }
}

这样称呼:

request.AddFormData(postParams);

答案 1 :(得分:0)

HttpWebRequest request = WebRequest.CreateHttp("" + url);
//we could move the content-type into a function argument too.
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
postParams.Add("oauth_token", ""); // where do I add this to the request??
try
{
    //this is how you do it
    using(var stream = await request.GetRequestStreamAsync())
    {
        byte[] jsonAsBytes = Encoding.UTF8.GetBytes(string.Join("&", postParams.Select(pp => pp.Key + "=" + pp.Value)));
        await stream.WriteAsync(jsonAsBytes, 0, jsonAsBytes.Length);
    }
    HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync();

    Debug.WriteLine(response.ContentType);
    System.IO.Stream responseStream = response.GetResponseStream();
    string data;
    using (var reader = new System.IO.StreamReader(responseStream))
    {
        data = reader.ReadToEnd();
    }
    responseStream.Close();

    return data;
}

Async Await HttpWebRequest Extensions:

public static class HttpExtensions
{
    public static Task<Stream> GetRequestStreamAsync(this HttpWebRequest request)
    {
        var tcs = new TaskCompletionSource<Stream>();

        try
        {
            request.BeginGetRequestStream(iar =>
           {
               try
               {
                   var response = request.EndGetRequestStream(iar);
                   tcs.SetResult(response);
               }
               catch (Exception exc)
               {
                   tcs.SetException(exc);
               }
           }, null);
        }
        catch (Exception exc)
        {
            tcs.SetException(exc);
        }

        return tcs.Task;
    }
    public static Task<HttpWebResponse> GetResponseAsync(this HttpWebRequest request)
    {
        var taskComplete = new TaskCompletionSource<HttpWebResponse>();
        request.BeginGetResponse(asyncResponse =>
        {
            try
            {
                HttpWebRequest responseRequest = (HttpWebRequest)asyncResponse.AsyncState;
                HttpWebResponse someResponse =
                   (HttpWebResponse)responseRequest.EndGetResponse(asyncResponse);
                taskComplete.TrySetResult(someResponse);
            }
            catch (WebException webExc)
            {
                HttpWebResponse failedResponse = (HttpWebResponse)webExc.Response;
                taskComplete.TrySetResult(failedResponse);
            }
        }, request);
        return taskComplete.Task;
    }
}

通过扩展程序,我认为它有点清洁。