【问题标题】:Make an http post request to send a JSON file in WP7发出 http post 请求以在 WP7 中发送 JSON 文件
【发布时间】:2013-04-18 16:24:35
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

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

    wc.Encoding = Encoding.UTF8;
    
    wc.UploadStringCompleted += new UploadStringCompletedEventHandler(wc_UploadStringCompleted);   
    
    wc.UploadStringAsync(URI,"POST","Data_To_Be_sent");    
    

    【讨论】:

    • 我还收到一个错误,即“wc_cart_session”在当前上下文中不存在。那么“要发送的数据”呢?似乎它应该是一个字符串。但是如果我需要发送一个 UTF8 格式的字节数组呢?
    • wc替换wc_cart_session(我复制/粘贴了你的代码)。
    • hm 可能是的,但这就是教程中的内容,我认为这是一个特殊的 var 或 smth。
    • 我认为您需要更多地阅读 C# 以了解这里发生了什么。阅读我的答案中的Encoding 链接。它解释了如何将字符串转换为字节数组。
    猜你喜欢
    • 1970-01-01
    • 2012-12-04
    • 1970-01-01
    • 1970-01-01
    • 2013-02-27
    • 2018-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多