来自windows phone 8的Http GET请求
本文关键字:Http GET 请求 windows phone 来自 | 更新日期: 2023-09-27 17:50:21
此代码适用于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);
}
但是我想从windowsphone 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客户端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);
}