c# - 在 WP7 中发出 http post 请求发送 JSON 文件

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

我想将 JSON 文件从我的 WP7 设备发送到我的本地服务器。在 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 类有一个 Encoding UploadStringAsyncDownloadStringAsync 方法使用的属性。在那里设置您的编码。

wc.Encoding = Encoding.UTF8;

wc.UploadStringCompleted += new UploadStringCompletedEventHandler(wc_UploadStringCompleted);   

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

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

相关文章:

c# - 在 slack 上发布带有附加文件的消息

c# - 使用 Facebook SDK .NET 发布消息

html - 在 Windows Phone 7 应用程序中流式传输音频

c# - 如何限制文本框的表情符号范围 u2600-u26FF

windows-phone-7 - 如何在 Windows 手机应用程序中实现错误日志记录?

javascript - 无法使用ajax将文件发送到php文件

forms - 在 Perl 中发布文件时出错

c# - 来自单选按钮列表选择的数字文本框控件

javascript - 如何获取当前页面的 ID 或在 WordPress 中发帖?

c# - 直接通过C#中的实例连接