来自Windows Phone 8的Http GET请求

时间:2014-03-15 16:58:21

标签: c# windows-phone-8

此代码适用于Windows窗体:

string URI = "http://localhost/1/index.php?dsa=232323";
string myParameters = "";

using (WebClient wc = new WebClient())
{
    wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
    string HtmlResult = wc.UploadString(URI, myParameters);
}

但我想从Windows Phone 8发送http GET请求。在wp 8中,没有方法UploadString()等......

4 个答案:

答案 0 :(得分:6)

只需使用HttpClient

即可
using(HttpClient hc = new HttpClient())
{
    var response = await hc.PostAsync(url,new StringContent (yourString));
}

对于您的情况,您可以上传FormUrlEncodedContent内容,而不是手动形成上传字符串。

using(HttpClient hc = new HttpClient())
{
    var keyValuePairs = new Dictionary<string,string>();
    // Fill keyValuePairs

    var content = new FormUrlEncodedContent(keyValuePairs);

    var response = await hc.PostAsync(url, content);
}

答案 1 :(得分:0)

试试HTTP Client NuGet库。它适用于Windows Phone 8。

答案 2 :(得分:0)

对于GET方法,您可以将字符串与URI本身一起提供。

private void YourCurrentMethod()
{
    string URI = "http://localhost/1/index.php?dsa=232323";
    string myParameters = "";

    URI = URI + "&" + myParameters; 

    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URI);

    request.ContentType="application/x-www-form-urlencoded";

    request.BeginGetResponse(GetResponseCallback, request);
}

void GetResponseCallback(IAsyncResult result)
{
    HttpWebRequest request = result.AsyncState as HttpWebRequest;
    if (request != null)
    {
        try
        {
            WebResponse response = request.EndGetResponse(result);
            //Do what you want with this response
        }
        catch (WebException e)
        {
            return;
        }
    }
}

答案 3 :(得分:-2)

这里已经回答:Http Post for Windows Phone 8 - 你会想要这样的东西:

// server to POST to
string url = "myserver.com/path/to/my/post";

// HTTP web request
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "text/plain; charset=utf-8";
httpWebRequest.Method = "POST";

// Write the request Asynchronously 
using (var stream = await Task.Factory.FromAsync<Stream>(httpWebRequest.BeginGetRequestStream,          
                                                         httpWebRequest.EndGetRequestStream, null))
{
   //create some json string
   string json = "{ \"my\" : \"json\" }";

   // convert json to byte array
   byte[] jsonAsBytes = Encoding.UTF8.GetBytes(json);

   // Write the bytes to the stream
   await stream.WriteAsync(jsonAsBytes, 0, jsonAsBytes.Length);
}