我尝试使用POST数据发出Web请求并获取响应。我已经让它适用于Android,但它对Windows Phone的工作方式并不相同,而我似乎无法让它发挥作用。我目前收到GetRequestStreamd
和GetResponse
的错误。我已经使用async
和await
尝试了它,但它返回了空指针。我在Android中使用了以下代码:
public static string Login(string user, string pwd)
{
WebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("myurl");
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
LoginData data = new LoginData
{
userid = user,
password = pwd
};
var json = JsonConvert.SerializeObject(data);
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Dispose();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
return streamReader.ReadToEnd();
}
}
答案 0 :(得分:0)
我已经开始工作了!答案显示在下面的代码中。
public static string postData;
public static string responseString;
public static async Task PostJsonRequest()
{
string AuthServiceUri = "myurl";
HttpWebRequest spAuthReq = WebRequest.Create(AuthServiceUri) as HttpWebRequest;
spAuthReq.ContentType = "application/json";
spAuthReq.Method = "POST";
spAuthReq.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), spAuthReq);
}
public static void GetRequestStreamCallback(IAsyncResult callbackResult)
{
HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
Stream postStream = myRequest.EndGetRequestStream(callbackResult);
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Dispose();
myRequest.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallback), myRequest);
}
public static void GetResponsetStreamCallback(IAsyncResult callbackResult)
{
try
{
HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
Stream streamResponse = response.GetResponseStream();
StreamReader reader = new StreamReader(streamResponse);
responseString = reader.ReadToEnd();
streamResponse.Dispose();
reader.Dispose();
response.Dispose();
}
catch (Exception e)
{
}
}
public static void EnterLoginValues(string user, string pwd)
{
LoginData data = new LoginData
{
userid = user,
password = pwd
};
postData = JsonConvert.SerializeObject(data);
}