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. 如何把apache和nginx 加入到系统服务,用service 命令来控制启动、停止

    1 把apache 加入到系统服务,即用service 命令来控制Apache 启动.停止  如果Linux服务器上默认安装了httpd的话(用rpm -qa|grep httpd查看),那你就可以用 ...

  2. 1、elasticsearch简介

    1.elasticsearch简介 中文帮助文档地址:http://es.xiaoleilu.com/ • Elasticsearch是一个基于Lucene的实时的分布式搜索和分析引擎.设计用于云计算 ...

  3. .NET MySQL的参数化查询

    MySqlConnection conn = new MySqlConnection(SqlConnnectString); MySqlCommand cmd = new MySqlCommand(& ...

  4. C# DES 加密解密

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.S ...

  5. Sql Server相关的性能计数器

    OS Memory and Paging 性能计数器: 1.Memory\Availability Mbytes   未使用的物理内存(非页面文件),通常情况下它应该大于100MB 2.Memory\ ...

  6. typedef和define的作用域

    typedef: 如果放在所有函数之外,它的作用域就是从它定义开始直到文件尾: 如果放在某个函数内,定义域就是从定义开始直到该函数结尾: #define: 不管是在某个函数内,还是在所有函数之外,作用 ...

  7. Floyd算法(弗洛伊德算法)

    算法描述: Floyd算法又称为弗洛伊德算法,插点法,是一种用于寻找给定的加权图中顶点间最短路径的算法.从图的带权邻接矩阵A=[a(i,j)] n×n开始,递归地进行n次更新,即由矩阵D(0)=A,按 ...

  8. GDAL 生成shp文件

    附件:http://pan.baidu.com/s/1i3GPwrV(C#版GDAL接口.dll) 示例程序: http://pan.baidu.com/s/1jpIKQ  (程序是在vs2008 x ...

  9. js获取当期日期累加天数

    本文是转载的,,忘记出处了,我用上了,也给大家分享一下 一.日期减去天数等于第二个日期 function cc(dd,dadd)...{//可以加上错误处理var a = new Date(dd)a ...

  10. Linux下,命令 wget 的使用

    wget是一个从网络上自动下载文件的自由工具.它支持HTTP,HTTPS和FTP协议,可以使用HTTP代理.  所谓的自动下载是指,wget可以在用户退出系统的之后在后台执行.这意味这你可以登录系统, ...