代码之家  ›  专栏  ›  技术社区  ›  donparalias

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

  •  2
  • donparalias  · 技术社区  · 13 年前

    我想发一封 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 回复  |  直到 13 年前
        1
  •  2
  •   keyboardP    13 年前

    这个 WebClient 类有一个 Encoding UploadStringAsync DownloadStringAsync 方法使用。在那里设置编码。

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