IOS5开发-http get/post调用mvc4 webapi互操作(图片上传)

 

目前最流行的跨平台交互是采用http协议通过JSON对象进行互操作。这种方式最简单,也很高效。webservice+xml的方式似乎已经过时。

下面是我做的一个例子

webapi的代码

public IEnumerable<Product> GetAllProducts()
{
Console.WriteLine(DateTime.Now.ToLongTimeString() + " : receive request.");
return new List<Product>
{
new Product() { Id = 1, Name = "Gizmo 1", Price = 1.99M },
new Product() { Id = 2, Name = "Gizmo 2", Price = 2.99M },
new Product() { Id = 3, Name = "Gizmo 3", Price = 3.99M },
new Product() { Id = 4, Name = "TShirt 3", Price = 5.99M },
new Product() { Id = 5, Name = "SOFT TSHIRT", Price = 34.99M },
};
}

public Product GetProductById(int id)
{
if (id < 1 || id > 3)
{
throw new HttpResponseException(System.Net.HttpStatusCode.NotFound);
}
return new Product()
{
Id = id,
Name = "Gizmo " + id.ToString(),
Price = id + 0.99M
};
}
// POST /api/Products
public Product Post(Product p)
{
Console.WriteLine(string.Format("submit Name:{0},Price:{1}",p.Name,p.Price));
return p;
}

// POST /api/Upload
public string Post()
{
Console.WriteLine(DateTime.Now.ToLongTimeString() + " : receive upload request.");
if (!Request.Content.IsMimeMultipartContent("form-data"))
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
MultipartFormDataStreamProvider streamProvider = new MultipartFormDataStreamProvider();

// Read the MIME multipart content using the stream provider we just created.
IEnumerable<HttpContent> bodyparts = Request.Content.ReadAsMultipartAsync(streamProvider).Result;

// The submitter field is the entity with a Content-Disposition header field with a "name" parameter with value "submitter"
//string submitter = "submitter";
//if (!bodyparts.TryGetFormFieldValue("submitter", out submitter))
//{
// submitter = "unknown";
//}

// Get a dictionary of local file names from stream provider.
// The filename parameters provided in Content-Disposition header fields are the keys.
// The local file names where the files are stored are the values.
IDictionary<string, string> bodyPartFileNames = streamProvider.BodyPartFileNames;

// Create response containing information about the stored files.
return bodyPartFileNames.Select(kv =>
{

FileInfo fileinfo = new FileInfo(kv.Value);
Console.WriteLine("receive file name:" + fileinfo.FullName + " Size:" + fileinfo.Length.ToString());
return new FileResult
{
FileName = kv.Key,
// LocalPath = fileinfo.FullName,
// LastModifiedTime = fileinfo.LastWriteTimeUtc,
// Length = fileinfo.Length,
// Submitter = submitter
};

//return FileResult;
}).ToList()[0].FileName;


public IEnumerable<Product> GetAllProducts()
        {
            Console.WriteLine(DateTime.Now.ToLongTimeString() + " : receive request.");
            return new List<Product> 
            {
                new Product() { Id = 1, Name = "Gizmo 1", Price = 1.99M },
                new Product() { Id = 2, Name = "Gizmo 2", Price = 2.99M },
                new Product() { Id = 3, Name = "Gizmo 3", Price = 3.99M },
                new Product() { Id = 4, Name = "TShirt 3", Price = 5.99M },
                new Product() { Id = 5, Name = "SOFT TSHIRT", Price = 34.99M },
            };
        }         public Product GetProductById(int id)
        {
            if (id < 1 || id > 3)
            {
                throw new HttpResponseException(System.Net.HttpStatusCode.NotFound);
            }
            return new Product()
            {
                Id = id,
                Name = "Gizmo " + id.ToString(),
                Price = id + 0.99M
            };
        }
        // POST /api/Products
        public Product Post(Product p)
        {
            Console.WriteLine(string.Format("submit Name:{0},Price:{1}",p.Name,p.Price));
            return p;
        }
        
 // POST /api/Upload
        public string Post()
        {
            Console.WriteLine(DateTime.Now.ToLongTimeString() + " : receive upload request.");
            if (!Request.Content.IsMimeMultipartContent("form-data"))
           {
               throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }
            MultipartFormDataStreamProvider streamProvider = new MultipartFormDataStreamProvider();             // Read the MIME multipart content using the stream provider we just created.
            IEnumerable<HttpContent> bodyparts = Request.Content.ReadAsMultipartAsync(streamProvider).Result;             // The submitter field is the entity with a Content-Disposition header field with a "name" parameter with value "submitter"
            //string submitter = "submitter";
            //if (!bodyparts.TryGetFormFieldValue("submitter", out submitter))
            //{
            //    submitter = "unknown";
            //}             // Get a dictionary of local file names from stream provider.
            // The filename parameters provided in Content-Disposition header fields are the keys.
            // The local file names where the files are stored are the values.
            IDictionary<string, string> bodyPartFileNames = streamProvider.BodyPartFileNames;             // Create response containing information about the stored files.
            return bodyPartFileNames.Select(kv =>
            {
              
                FileInfo fileinfo = new FileInfo(kv.Value);
                Console.WriteLine("receive file name:" + fileinfo.FullName + " Size:" + fileinfo.Length.ToString());
                return new FileResult
                {
                    FileName = kv.Key,
                   // LocalPath = fileinfo.FullName,
                   // LastModifiedTime = fileinfo.LastWriteTimeUtc,
                   // Length = fileinfo.Length,
                   // Submitter = submitter
                };
                
                //return FileResult;
            }).ToList()[0].FileName;

webapi 返回的IEnumerable<Product> 或 IQueryable<Product> 支持odata协议,odata协议功能很强大,查询很方便。可以关注。

第一个是通过http get/post获取服务端数据和更新服务端数据。

代码获取数据代码


- (IBAction)getAction:(id)sender {
    NSString *urlstring=self.urlTextField.text;
    NSURL *url=[NSURL URLWithString:urlstring];
    //NSData *jsondata=[[NSData alloc]initWithContentsOfURL:url];
    //NSLog(@"data:%@",[[NSString alloc] initWithData:jsondata encoding:NSUTF8StringEncoding]);
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
    NSOperationQueue *queue=[[NSOperationQueue alloc] init];
    [NSURLConnection sendAsynchronousRequest:request queue:queue
                           completionHandler:^(NSURLResponse *respone,
                                               NSData *data,
                                               NSError *error)
     {
         if ([data length]>0 && error==nil) {
             NSString *jsonstring=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
             //[self.respondTextView setText:jsonstring];
             NSLog(@"data:%@",jsonstring);
             //[self performSelectorOnMainThread:@selector(setRespondtext:)withObject:jsonstring waitUntilDone:YES modes:nil];
             [self performSelectorOnMainThread:@selector(setRespondtext:) withObject:data waitUntilDone:NO];
         }  
     }
     ];
    

}

post数据代码如下


- (IBAction)postAction:(id)sender {
    NSString *urlstring=self.urlTextField.text;
    NSString *poststr=self.requestTextView.text;
    
    NSURL *url=[NSURL URLWithString:urlstring];
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
    [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:[poststr dataUsingEncoding:NSUTF8StringEncoding]];
    NSOperationQueue *queue=[[NSOperationQueue alloc] init];
    [NSURLConnection sendAsynchronousRequest:request queue:queue
                           completionHandler:^(NSURLResponse *respone,
                                               NSData *data,
                                               NSError *error)
     {
         if ([data length]>0 && error==nil) {
             NSString *jsonstring=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
             //[self.respondTextView setText:jsonstring];
             NSLog(@"data:%@",jsonstring);
             //[self performSelectorOnMainThread:@selector(setRespondtext:)withObject:jsonstring waitUntilDone:YES modes:nil];
             [self performSelectorOnMainThread:@selector(setRespondtext:) withObject:data waitUntilDone:NO];
         }  
     }
     ];    
    
    

}

解析获取的JSON字符串


-(void) setRespondtext:(NSData *)data{
    NSString *text=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    id jsonObject=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
    if (jsonObject !=nil) {
        NSLog(@"Successfully deserialized...");
        if ([jsonObject isKindOfClass:[NSDictionary class]]) {
            NSDictionary *deserializedDic=(NSDictionary *)jsonObject;
            NSLog(@"Dersialized Json dictionary =%@",deserializedDic);
        }
        else if([jsonObject isKindOfClass:[NSArray class]]){
            NSArray *deserializedArray=(NSArray *)jsonObject;
            NSLog(@"Derialized json array = %@",deserializedArray);
            for (NSDictionary *item in deserializedArray) {
                NSLog(@"Id : %@ Name: %@ Price : %@",[item objectForKey:@"Id"],[item objectForKey:@"Name"],[item objectForKey:@"Price"]);
            }
        }else{
            
        }
    }
    
    
    [self.respondTextView setText:text];

}

图片上传的代码


- (IBAction)uploadAction:(id)sender {
    NSString *urlstring=self.urlTextField.text;
    //NSString *poststr=@"";
    NSData *imgData=UIImageJPEGRepresentation(self.previewImageView.image, 0.9f);
    
    NSString *boundary = @"0xKhTmLbOuNdArY";  
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary, nil];
    
    NSURL *url=[NSURL URLWithString:urlstring];
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
    [request addValue:contentType forHTTPHeaderField:@"Content-Type"];
    [request setHTTPMethod:@"POST"];
    NSMutableData *body = [NSMutableData data];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"iphonefile.jpg\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[NSData dataWithData:imgData]];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    
    [request setHTTPBody:body];
    NSOperationQueue *queue=[[NSOperationQueue alloc] init];
    [NSURLConnection sendAsynchronousRequest:request queue:queue
                           completionHandler:^(NSURLResponse *respone,
                                               NSData *data,
                                               NSError *error)
     {
         if ([data length]>0 && error==nil) {
             NSString *jsonstring=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
             //[self.respondTextView setText:jsonstring];
             NSLog(@"data:%@",jsonstring);
             //[self performSelectorOnMainThread:@selector(setRespondtext:)withObject:jsonstring waitUntilDone:YES modes:nil];
             //[self performSelectorOnMainThread:@selector(setRespondtext:) withObject:data waitUntilDone:NO];
         }  
     }
     ];    

}

我感觉使用ios sdk自带的NSMutableURLRequest,NSURLConnection, NSJSONSerialization,也非常方便,似乎没有必要去使用第三方的类库。

IOS5开发-http get/post调用mvc4 webapi互操作(图片上传)[转]的更多相关文章

  1. .NET WebAPI 实现图片上传(包括附带参数上传图片)

    博主的项目,客户端是APP,考虑到以后也可能会应用到微信端.网站等,图片上传方法就需要兼容多端,并且以目前的设计,不允许非登录用户上传图片,就得在上传时解决附带参数上传图片的问题. 先来看看后台方法( ...

  2. 微信公共服务平台开发(.Net 的实现)8-------处理图片(上传下载发送)

    举个例子,有人对着我们的公共微信号拍个照片发送过来,然后我们处理这个照片,比如进行ocr识别字(随后就会降到这个例子),或者人脸识别,或者拍照取证等,这些功能都是相当有用的.那么我们现在就要分析一下这 ...

  3. Dynamics CRM 365中结合注释和WebApi实现图片上传

    首先需要在实体上使用注释,然后在窗体上引用WebResource. WebResource的代码: <!DOCTYPE html> <html> <head> &l ...

  4. C#设计模式总结 C#设计模式(22)——访问者模式(Vistor Pattern) C#设计模式总结 .NET Core launch.json 简介 利用Bootstrap Paginator插件和knockout.js完成分页功能 图片在线裁剪和图片上传总结 循序渐进学.Net Core Web Api开发系列【2】:利用Swagger调试WebApi

    C#设计模式总结 一. 设计原则 使用设计模式的根本原因是适应变化,提高代码复用率,使软件更具有可维护性和可扩展性.并且,在进行设计的时候,也需要遵循以下几个原则:单一职责原则.开放封闭原则.里氏代替 ...

  5. 微信小程序开发之多图片上传+服务端接收

    前言: 业务需求,这次需要做一个小程序同时选中三张图片一起上传到服务端,后端使用的.NET WEBAPI接收数据保存. 使用技术: 在这章中将会使用到微信小程序wx.uploadFile(Object ...

  6. MVC4中基于bootstrap和HTML5的图片上传Jquery自定义控件

    场景:mvc4中上传图片,批量上传,上传前浏览,操作.图片进度条. 解决:自定义jquery控件 没有解决:非图片上传时,会有浏览样式的问题; 解决方案; 1.样式 – bootstrap 的css和 ...

  7. kindeditor修改图片上传路径-使用webapi上传图片到图片服务器

    kindeditor是一个非常好用的富文本编辑器,它的简单使用我就不再介绍了. 在这里我着重介绍一些使用kindeditor修改图片上传路径并通过webapi上传图片到图片服务器的方案. 因为我使用的 ...

  8. kindeditor扩展粘贴图片功能&修改图片上传路径并通过webapi上传图片到图片服务器

    前言 kindeditor是一个非常好用的富文本编辑器,它的简单使用我就不再介绍了. 而kindeditor却对图片的处理不够理想. 本篇博文需要解决的问题有两个: kindeditor扩展粘贴图片功 ...

  9. Java微信公众平台开发_07_JSSDK图片上传

    一.本节要点 1.获取jsapi_ticket //2.获取getJsapiTicket的接口地址,有效期为7200秒 private static final String GET_JSAPITIC ...

随机推荐

  1. [置顶] Android开发实战记录(三)---HelloWorld

    1.新建Android项目,选择Android Project,然后Next 2.填写项目名称HelloWorld然后next,这里注意下,Java开发的命名规范 3.选择Android SDK版本, ...

  2. poj 3894 System Engineer (二分图最大匹配--匈牙利算法)

    System Engineer Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 507   Accepted: 217 Des ...

  3. Hacker(三)之黑客定位目标---IP

    IP即Internet Protocol的简称,中文简称"网协",是为计算机网络相互连接进行通信而设计的协议.无论何种操作系统,只要遵守IP协议就可以与Internet互联互通. ...

  4. 一.Linq to JSON是用来干什么的?

    Linq to JSON是用来操作JSON对象的.可以用于快速查询,修改和创建JSON对象.当JSON对象内容比较复杂,而我们仅仅需要其中的一小部分数据时,可以考虑使用Linq to JSON来读取和 ...

  5. 手工启动oracle EM

    在WINDOWS上安完ORACLE发现没有EM没有启动,在网上找了一个手工启动的方法,试了,在WIN下同样可用. 人家的原文如下: oracle@linux:~> sqlplus/ as sys ...

  6. 【转载自友盟消息推送iOS文档】在appDelegate中注册推送

    1.2   基本功能集成指南 提示 请先在友盟的消息推送管理后台中创建App,获得AppKey和AppSecret 导入SDK 下载 UMessage_Sdk_All_x.x.x.zip并解压缩 导入 ...

  7. 学习asp.net比较完整的流程

    如果你已经有较多的面向对象开发经验,跳过以下这两步: 第一步 掌握一门.NET面向对象语言,C#或VB.NET 我强烈反对在没系统学过一门面向对象(OO)语言的前提下去学ASP.NET. ASP.NE ...

  8. javascript 事件代理及应用

    事件代理又叫事件委托在前端发开中实际是非常有用的,说事件代理之前我们先说说事件绑定 <p onclick="test()" ></p> function t ...

  9. HDU 2653 - Waiting ten thousand years for Love

    首先,对于一个 '@' 飞上去,飞下来都要耗1点魔力,所以是两点= = 然后站在同一格 魔力可能不同,所以要增加一维. 还有当前搜到的不一定是最小. 别的也没啥. #include <iostr ...

  10. [Linked List]Insertion Sort List

    Total Accepted: 59422 Total Submissions: 213019 Difficulty: Medium Sort a linked list using insertio ...