我正试图用POST数据发出一个web请求并返回响应。我已经让它在安卓系统上工作了,但它在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();
}
}
我已经开始工作了!答案显示在下面的代码中。
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);
}