簡體   English   中英

來自Windows Phone 8的Http GET請求

[英]Http GET request from 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()等...

只需使用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);
}

嘗試HTTP Client NuGet庫。 它適用於Windows Phone 8。

對於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;
        }
    }
}

已經在這里回答: Windows Phone 8的Http Post - 你會想要這樣的東西:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM