How to send POST request with parameters asynchron

2020-04-21 00:26发布

I would like to send POST request in windows phone 8 environment my code is running successfully but i am getting NotFound exception. Its mean is i want to POST some data but i am sending null. So please let me know how to send POST Request asynchronously with Data in windows phone 8 environmet. I tried following links but not helpful. link link2

I approached like this

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)
    {
    }
}

As far as i know notFound exceptions comes when we are not posting any data while using the POST request method. you can see i have mentioned the data i am passing into the GEtRequestStreamCallback. I have mentioned a note. Please help me. Where i am going to wrong.

2条回答
放我归山
2楼-- · 2020-04-21 00:37

I did it with the help of HttpClient inplace of WebClient. Following few lines will do magic. :)

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;
查看更多
Animai°情兽
3楼-- · 2020-04-21 00:44

Try setting the content-type to application/json; charset=utf-8

Also, you can do all that stuff in nicer and shorter way(sample):

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);
查看更多
登录 后发表回答