在monotouch中使用NSMutableURLRequest调用webservice

时间:2013-08-20 07:10:17

标签: xamarin.ios parameter-passing

我尝试将捕获图像从iPhone保存到服务器。我完成了Xcode。像

这样的代码
NSMutableURLRequest  *request= [NSMutableURLRequest requestWithURL:url];

[request setHTTPMethod:@"POST"];

NSString *boundary = @"---------------------------14737809831466499882746641449";

NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];

[request addValue:contentType forHTTPHeaderField: @"Content-Type"];

NSMutableData *body = [NSMutableData data];

[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: attachment; name=\"%@\" filename=\"Test.png\"\r\n", imgName] dataUsingEncoding:NSUTF8StringEncoding]]; 
[body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

[request setHTTPBody:body];

NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:delegate];

现在我尝试使用monotouch,

这里我创建连接,发送请求&收到回复工作正常。

但在这里我不知道如何设置Header& Body to NSMutableURLRequest,我只需要知道如何传递参数(如上面的Xcode)。

NSMutableUrlRequest request = new NSMutableUrlRequest(new NSUrl("http://url.com"), NSUrlRequestCachePolicy.ReloadRevalidatingCacheData, 20);
request.HttpMethod = "POST";

var connectionDelegate = new TestNSURLConnectionDelegate();
var connection = new NSUrlConnection(request, connectionDelegate);
connection.Start();

任何人都可以帮助我......

1 个答案:

答案 0 :(得分:0)

使用System.Net访问HttpWebRequest。

您只需要发布到网址..并将图片的byte []写入请求正文。

在我的例子中...... ServiceBase值映射到静态字符串,“Service.SubmitImage”是指向服务方法端点的静态字符串。

 public void SubmitImage(byte[] image)
    {
        var request = WebRequest.Create(ServiceBase + Service.SubmitImage);
        request.Method = "POST";
        request.ContentType = "application/octet-stream";
        request.ContentLength = image.Length;
        Stream str = request.GetRequestStream();
        str.Write(image, 0, image.Length);
        str.Close();
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    }