IOS5开发-http get/post调用mvc4 webapi互操作(图片上传)[转]
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互操作(图片上传)[转]的更多相关文章
- .NET WebAPI 实现图片上传(包括附带参数上传图片)
博主的项目,客户端是APP,考虑到以后也可能会应用到微信端.网站等,图片上传方法就需要兼容多端,并且以目前的设计,不允许非登录用户上传图片,就得在上传时解决附带参数上传图片的问题. 先来看看后台方法( ...
- 微信公共服务平台开发(.Net 的实现)8-------处理图片(上传下载发送)
举个例子,有人对着我们的公共微信号拍个照片发送过来,然后我们处理这个照片,比如进行ocr识别字(随后就会降到这个例子),或者人脸识别,或者拍照取证等,这些功能都是相当有用的.那么我们现在就要分析一下这 ...
- Dynamics CRM 365中结合注释和WebApi实现图片上传
首先需要在实体上使用注释,然后在窗体上引用WebResource. WebResource的代码: <!DOCTYPE html> <html> <head> &l ...
- C#设计模式总结 C#设计模式(22)——访问者模式(Vistor Pattern) C#设计模式总结 .NET Core launch.json 简介 利用Bootstrap Paginator插件和knockout.js完成分页功能 图片在线裁剪和图片上传总结 循序渐进学.Net Core Web Api开发系列【2】:利用Swagger调试WebApi
C#设计模式总结 一. 设计原则 使用设计模式的根本原因是适应变化,提高代码复用率,使软件更具有可维护性和可扩展性.并且,在进行设计的时候,也需要遵循以下几个原则:单一职责原则.开放封闭原则.里氏代替 ...
- 微信小程序开发之多图片上传+服务端接收
前言: 业务需求,这次需要做一个小程序同时选中三张图片一起上传到服务端,后端使用的.NET WEBAPI接收数据保存. 使用技术: 在这章中将会使用到微信小程序wx.uploadFile(Object ...
- MVC4中基于bootstrap和HTML5的图片上传Jquery自定义控件
场景:mvc4中上传图片,批量上传,上传前浏览,操作.图片进度条. 解决:自定义jquery控件 没有解决:非图片上传时,会有浏览样式的问题; 解决方案; 1.样式 – bootstrap 的css和 ...
- kindeditor修改图片上传路径-使用webapi上传图片到图片服务器
kindeditor是一个非常好用的富文本编辑器,它的简单使用我就不再介绍了. 在这里我着重介绍一些使用kindeditor修改图片上传路径并通过webapi上传图片到图片服务器的方案. 因为我使用的 ...
- kindeditor扩展粘贴图片功能&修改图片上传路径并通过webapi上传图片到图片服务器
前言 kindeditor是一个非常好用的富文本编辑器,它的简单使用我就不再介绍了. 而kindeditor却对图片的处理不够理想. 本篇博文需要解决的问题有两个: kindeditor扩展粘贴图片功 ...
- Java微信公众平台开发_07_JSSDK图片上传
一.本节要点 1.获取jsapi_ticket //2.获取getJsapiTicket的接口地址,有效期为7200秒 private static final String GET_JSAPITIC ...
随机推荐
- 关于随机数字K线极值的统计结果
如果有组随机数字,如数字彩票.我们对号码进行平均二分后,统计期出现的结果分布,对结果分布进行K线累加,得到一条折线. 这条折线的顶点和底点的统计上服从以下规则: 令总期数为N,统计区间为M,则在N期内 ...
- 格而知之4:寻找EXC_BAD_ACCESS
EXC_BAD_ACCESS算是一个比较常见的错误,大部分情况下,它出现在某个对象还未初始化或已被释放后,还去试图访问这个对象的时候,即是在出现悬挂指针的时候(当然也有非悬挂指针导致的EXC_BAD_ ...
- c# 图片简单模糊 非高斯模糊
/// <summary> /// 图像模糊化 /// </summary> /// <param name="bit ...
- LR实战之Discuz开源论坛——登录脚本检查点
在开发Discuz登录脚本时,遇到的一个问题是怎么去验证虚拟用户真正的登录成功,当然,熟悉LoadRunner工具的人就会知道,在脚本中使用检查点,对,没错! 我们知道,LR检查点功能有两种:文本检查 ...
- MPreview.js
Word,PPT 文档预览组件(图片预览组件) 移动端请移步 MPreview.mobile Demo参考 http://demo.webjyh.com/MPreview/ 特此说明 此插件是我在项目 ...
- 创建httpd启动脚本并加入启动列表开机启动
第一步: cp /usr/local/apache2/bin/apachectl /etc/init.d/httpd 第二步: vim /etc/init.d/httpd 在第一行#!/bin/s ...
- Lua编程入门-学习笔记2
第6章 深入函数 函数是一种“第一类值(First-Class Value)”,他们具有特定的词法域(lexical scoping) 将表达式“function(x) <body> en ...
- 奇葩问题:spring+mybaits项目突然出现其中一些Mapper类找不到
一.问题现象 1,No bean named 'bomManageMapper' found in org.springframework.beans.factory.support.DefaultL ...
- 调试 JavaScript 脚本
随着 JavaScript 应用的复杂性逐渐提高,开发者需要有力的调试工具来帮助他们快速发现问题的原因,并且能高效地修复它.Chrome DevTools 提供了一系列实用的工具使得调试 JavaSc ...
- 菜鸟的jQuery源码学习笔记(一)
整个jQuery是一个自调用的匿名函数: (function(global, factory) { if (typeof module === "object" && ...