发出http post请求以在WP7中发送JSON文件

时间:2013-04-18 16:24:36

标签: c# windows-phone-7 post http-headers httpwebrequest

我想发送JSON file from my WP7 device to my local server。在iOS上我使用了ASIHttpRequest库,我做的是:

//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;
    }

我如何在WP7应用程序中实现相同的功能?

到目前为止我发现了什么,我认为我很接近:

//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");    

}

其中:

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());            
  }
}

我认为“Data_to_be_Sent”应该是utf8编码中的jsonString?

修改


我注意到"Data_To_Be_sent"是一个字符串。但是这应该是UTF8编码吗?所以它应该是一个UTF8格式的字节数组。但是我只能在那里放一根绳子。我在这里缺少什么?

1 个答案:

答案 0 :(得分:2)

WebClient类具有UploadStringAsyncDownloadStringAsync方法使用的Encoding属性。在那里设置你的编码。

wc.Encoding = Encoding.UTF8;

wc.UploadStringCompleted += new UploadStringCompletedEventHandler(wc_UploadStringCompleted);   

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