Windows phone 8 如何在windows phone 8中异步发送带参数的POST请求

Windows phone 8 如何在windows phone 8中异步发送带参数的POST请求,windows-phone-8,http-post,async-await,webrequest,Windows Phone 8,Http Post,Async Await,Webrequest,我想在windows phone 8环境中发送POST请求。我的代码正在成功运行,但未发现异常。它的意思是我想发布一些数据,但我发送空。因此,请让我知道如何在WindowsPhone8环境中使用数据异步发送POST请求。我尝试了以下链接,但没有帮助。 我就这样走近 private async Task<LastRead> SyncLastReadPOST(LastRead lastreads, bool actionStatus) { string jsondata = "

我想在windows phone 8环境中发送POST请求。我的代码正在成功运行,但未发现异常。它的意思是我想发布一些数据,但我发送空。因此,请让我知道如何在WindowsPhone8环境中使用数据异步发送POST请求。我尝试了以下链接,但没有帮助。

我就这样走近

private async Task<LastRead> SyncLastReadPOST(LastRead lastreads, bool actionStatus)
{
    string jsondata = "";
    actionStatus = false;
    apiData = new LastReadAPI()//It is global variable from apiData this object has the information
    {
        AccessToken = thisApp.currentUser.AccessToken,
        Book = lastreads.Book,
        Page = lastreads.Page,
        Device = lastreads.Device
    };
    jsondata = Newtonsoft.Json.JsonConvert.SerializeObject(apiData);
    LastRead responsedData = new LastRead();
    Uri lastread_url = new Uri(string.Format("{0}lastread", url_rootPath));
    try
    {
        HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(lastread_url);
        webRequest.ContentType = "application/json";
        webRequest.Accept = "application/json;odata=verbose";
        webRequest.Method = "POST";
        webRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), webRequest);
    }
    catch { }
    return responsedData;
}

private void GetRequestStreamCallback(IAsyncResult ar)
{
    HttpWebRequest request = (HttpWebRequest)ar.AsyncState;
    Stream postStream = request.EndGetRequestStream(ar);
    var input = Newtonsoft.Json.JsonConvert.SerializeObject(jsondata);//jsondata is my global data variable in json format.
    byte[] byteArray = Encoding.UTF8.GetBytes(input);
    postStream.WriteAsync(byteArray, 0, byteArray.Length);
    postStream.Close();
    request.BeginGetResponse(new AsyncCallback(GetResponseStreamCallback), request);
}

private void GetResponseStreamCallback(IAsyncResult ar)
{
    try
    {
        HttpWebRequest webRequest = (HttpWebRequest)ar.AsyncState;
        HttpWebResponse response;
        //In following line i am getting the exception notFound.
        response = (HttpWebResponse)webRequest.EndGetResponse(ar);
        Stream streamResponse = response.GetResponseStream();
        StreamReader streamReaders = new StreamReader(streamResponse);
        var responces = streamReaders.ReadToEnd();
        streamResponse.Close();
        streamReaders.Close();
        response.Close();
    }
    catch(Exception ex)
    {
    }
}
专用异步任务SyncLastReadPOST(LastRead lastreads,bool actionStatus)
{
字符串jsondata=“”;
actionStatus=false;
apiData=new LastReadAPI()//它是apiData中的全局变量此对象具有以下信息
{
AccessToken=thisApp.currentUser.AccessToken,
书,
Page=lastreads.Page,
Device=lastreads.Device
};
jsondata=Newtonsoft.Json.JsonConvert.SerializeObject(apiData);
LastRead ResponseData=新的LastRead();
Uri lastread_url=新Uri(string.Format(“{0}lastread”,url_rootPath));
尝试
{
HttpWebRequestWebRequest=(HttpWebRequest)webRequest.Create(lastread\uURL);
webRequest.ContentType=“应用程序/json”;
webRequest.Accept=“application/json;odata=verbose”;
webRequest.Method=“POST”;
BeginGetRequestStream(新的AsyncCallback(GetRequestStreamCallback),webRequest);
}
捕获{}
返回响应数据;
}
私有void GetRequestStreamCallback(IAsyncResult ar)
{
HttpWebRequest请求=(HttpWebRequest)ar.AsyncState;
Stream postStream=request.EndGetRequestStream(ar);
var input=Newtonsoft.Json.JsonConvert.SerializeObject(jsondata);//jsondata是Json格式的全局数据变量。
byte[]byteArray=Encoding.UTF8.GetBytes(输入);
WriteAsync(byteArray,0,byteArray.Length);
postStream.Close();
BeginGetResponse(新的AsyncCallback(GetResponseStreamCallback),request);
}
私有void GetResponseStreamCallback(IAsyncResult ar)
{
尝试
{
HttpWebRequest webRequest=(HttpWebRequest)ar.AsyncState;
HttpWebResponse;
//在下面的一行中,我得到了notFound异常。
response=(HttpWebResponse)webRequest.EndGetResponse(ar);
streamResponse=response.GetResponseStream();
StreamReader streamReaders=新StreamReader(streamResponse);
var responces=streamReaders.ReadToEnd();
streamResponse.Close();
streamReaders.Close();
response.Close();
}
捕获(例外情况除外)
{
}
}

据我所知,当我们在使用POST请求方法时没有发布任何数据时,notFound异常就会出现。您可以看到,我提到了传递到GEtRequestStreamCallback的数据。我提到一张纸条。请帮帮我。我错在哪里。

尝试将内容类型设置为application/json;字符集=utf-8

此外,您可以用更好、更短的方式完成所有这些工作(示例):


我是在HttpClient代替WebClient的帮助下完成的。下面几行就行了。:)


您是否尝试过在Firefox中的HTTPposter(如HttpRequester)中发布API?您的观点是正确的。但代码必须先运行,我才能做这些事情。如果可能,请共享代码片段,并让我们知道执行环境(尝试从模拟器/设备发布到本地托管/实时web API)?在windows phone 8模拟器上执行时,我也会用代码更新我的问题。@gitesh.tyagi我现在已经更新了我的代码。请看一看。我错在哪里?请推荐。你使用的Gitesh逻辑很棒。但是有可能追踪到反应吗?因为我想从响应中创建一个对象,我将在调用UploadPOST_Data(myWrapperClass对象)函数的地方使用该响应。我使用上述方法,它似乎可以工作,但我不知道如何从这种方法中获取响应,因此我无法确认它是否工作。@AshishJain er。结果实际上是包含服务器响应的属性。(旁注:您应该检查错误和取消的属性,以确定上载是否完成)
var wc = new WebClient();
//SET AUTH HEADER IF NECESSARY
//wc.Headers["Authorization"] = "OAUTH "+TOKEN; 
wc.Headers["Content-Type"] = "application/json;charset=utf-8";
wc.UploadStringCompleted += (s, er) =>
{
   if (er.Error != null) MessageBox.Show("Error\n" + er.Error);
   else MessageBox.Show(er.Result);
};
string data = JsonConvert.SerializeObject(MY_DATA_OBJECT);
MessageBox.Show(data);
wc.UploadStringAsync(new Uri(POST_URI), "POST", data);
HttpClient hc = new HttpClient();
hc.BaseAddress = new Uri(annotation_url.ToString());
HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, myUrl);
HttpContent myContent = req.Content = new StringContent(myJsonString, Encoding.UTF8, "application/json");
var response = await hc.PostAsync(myUrl, myContent);

//Line for pull out the value of content key value which has the actual resposne.
string resutlContetnt = response.Content.ReadAsStringAsync().Result;
DataContractJsonSerializer deserializer_Json = new DataContractJsonSerializer(typeof(MyWrapperClass));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(resutlContetnt.ToString()));
AnnotateResponse = deserializer_Json.ReadObject(ms) as MyWrapperClass;