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. 【LeetCode练习题】Minimum Path Sum

    Minimum Path Sum Given a m x n grid filled with non-negative numbers, find a path from top left to b ...

  2. 456. 132 Pattern

    456. 132 Pattern Given an array of integers a1, a2, a3-an, judge if there exists the 132 pattern. 13 ...

  3. java打印菱形的简单方法

    代码: public class Diamond { /** * 测试main方法 */ public static void main(String[] args) { printDiamond(1 ...

  4. Error Correct System(模拟)

     Error Correct System Time Limit:2000MS     Memory Limit:262144KB     64bit IO Format:%I64d & %I ...

  5. easy ui 如何单个引用其中某个插件?

    记录一下这个方法,前端时间一直在纠结这个问题,后来听一些前辈讲解后才恍然大悟,要单独引用某个插件,我们需要重视的是:easyloaer.js ,easy ui的下载包中也有easyloader的dem ...

  6. Winpcap网络编程九之Winpcap实战,ARP协议获得MAC表及主机通信

    大家好,本次我们须要完毕的任务是: 完毕两台主机之间的数据通信(数据链路层) 仿真ARP协议获得网段内主机的MAC表 使用帧完毕两台主机的通信(Hello! I'm -) 声明:本文章的目的是为大家的 ...

  7. MVC4 jquery 样式 主题 用法(案例)

    MVC4已经自带了jquery,新建的项目,基本上什么都不用添加就可以运行,跑项目.(集成了那么多东西,jquery,modernizr,自带的默认权限,生成的模板,但是缺没有一个统一的文档或者什么去 ...

  8. linux下SSH远程连接服务慢解决方案

    1.适用命令及方案如下:[远程连接及执行命令]ssh -p22root@10.0.0.19ssh -p22 root@10.0.0.19 /sbin/ifconfig[远程拷贝:推送及拉取]scp - ...

  9. C# 枚举运用"位"操作和"或"操作

    定义: /// <summary> /// The js function type(the same as name). /// </summary> [Flags] pub ...

  10. Unhandled event loop exception 解决办法

    网上搜索了一下.对其他人有效的办法有两种: 1. 安装了adsafe  .卸载掉就可以了. 2.安装了流氓软件:百度杀毒. 卸载掉也解决问题了 我就是第三种情况.到现在还没解决的热.!. 谁还有更好的 ...