Make an http post request to send a JSON file in WP7

故事扮演 提交于 2019-12-08 01:36:59

问题


I would like to send a JSON file from my WP7 device to my local server. On iOS I used the ASIHttpRequest library and what I did was :

//send json file , using ASIHttpClass
NSURL *url = [NSURL URLWithString:urlStr];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
request.timeOutSeconds = TIME_OUT_SECONDS;
[request setRequestMethod:@"PUT"];

NSString *credentials= [self encodeCredentials];
[request addRequestHeader:@"Authorization" value:[[NSString alloc] initWithFormat:@"Basic %@",credentials]];
[request addRequestHeader:@"Content-Type" value:@"application/json; charset=utf-8"];        

[request appendPostData:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
[request startSynchronous];

if([request responseStatusCode]==200){
   return true;
} else {
     return false;
    }

How could I implement the same functionality in my WP7 application?

What i ve found till now and i think i am close :

//Making a POST request using WebClient.

Function()
{    
  WebClient wc = new WebClient();

  var URI = new Uri("http://your_uri_goes_here");

  wc.Headers["Authorization"] = "Basic (here goes my credentials string which i have)";

  wc.Headers["Content-Type"] = "application/json; charset=utf-8";

 wc.UploadStringCompleted += new UploadStringCompletedEventHandler(wc_UploadStringCompleted);

 wc_cart_session.UploadStringAsync(URI,"POST","Data_To_Be_sent");    

}

where :

void wc__UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{  
  try            
  {          
     MessageBox.Show(e.Result); 
//e.result fetches you the response against your POST request.
 }
  catch(Exception exc)         
  {             
     MessageBox.Show(exc.ToString());            
  }
}

I suppose that the "Data_to_be_Sent" should be the jsonString in utf8 encoding?

EDIT


I have noticed that the "Data_To_Be_sent" is a string. However this should be in UTF8 encoding right? So it should be a an array of bytes which are in UTF8 format. However i can only place a string there. What am i missing here?


回答1:


The WebClient class has an Encoding property which the UploadStringAsync and DownloadStringAsync methods use. Set your encoding there.

wc.Encoding = Encoding.UTF8;

wc.UploadStringCompleted += new UploadStringCompletedEventHandler(wc_UploadStringCompleted);   

wc.UploadStringAsync(URI,"POST","Data_To_Be_sent");    


来源:https://stackoverflow.com/questions/16088288/make-an-http-post-request-to-send-a-json-file-in-wp7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!