我想发送一个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格式的字节数组。但是我只能在这里放一个字符串。我在这里想念什么?

最佳答案

WebClient类具有UploadStringAsyncDownloadStringAsync方法使用的Encoding属性。在此处设置编码。

wc.Encoding = Encoding.UTF8;

wc.UploadStringCompleted += new UploadStringCompletedEventHandler(wc_UploadStringCompleted);

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

关于c# - 发出http发布请求以在WP7中发送JSON文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16088288/

10-10 21:40