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 ...
随机推荐
- Zookeeper 2、Zookeeper的安装和配置(集群模式)
1.下载与解压 Zookeeper下载地址:http://www.apache.org/dyn/closer.cgi/zookeeper/ 下载完成以后解压到一个特定目录 同步时间所有节点的时间,并关 ...
- poj 3301 Texas Trip(几何+三分)
Description After a day trip with his friend Dick, Harry noticed a strange pattern of tiny holes in ...
- TRIZ系列-创新原理-32-改变颜色原理
改变颜色原理的详细描写叙述例如以下:1)改变物体或其环境的颜色:2)改变物体或其环境的透明度:3)对于难以看到的物体或过程.使用颜色加入剂来观測.4)假设已经使用了这样的加入剂,那么使用发光跟踪或原子 ...
- static_cast
C 风格(C-style)强制转型例如以下: (T) exdivssion // cast exdivssion to be of type T 函数风格(Function-style)强制转型使用这 ...
- oracle主机修改IP后客户端无法连接
无论SQLPLUS还是PLSQL Developer连接均报错: ERROR:ORA-12154: TNS: 无法解析指定的连接标识符 解决方法:修改主机IP后,客户端修改tnsnames文件IP:还 ...
- 「前端开发者」如何把握住「微信小程序」这波红利?
由于前两周一直在老家处理重要事情,虽然朋友圈被「微信小程序」刷爆了,但并没有时间深入了解. 昨天回广州之后,第一件事情就是把「微信小程序」相关的文章.开发文档.设计规范全部看了一遍,基本上明白了「微信 ...
- 用户"IIS APPPOOL\xxxxxxxx"登录失败解决方案
Server Error in '/' Application.-------------------------------------------------------------------- ...
- Android 判断文件的类型
import java.util.HashMap; import java.util.Iterator; /** * 判断文件的类型 */ public class MediaFileUtil { p ...
- .NET进阶系列之一:C#正则表达式整理备忘
有一段时间,正则表达式学习很火热很潮流,当时在CSDN一天就能看到 好几个正则表达式的帖子,那段时间借助论坛以及Wrox Press出版的<C#字符串和正则表达式参考手册>学习了一些基础的 ...
- 初识nginx+tomcat
百度百科说: Nginx ("engine x") 是一个高性能的HTTP和反向代理服务器,也是一个IMAP/POP3/SMTP服务器.Nginx是由Igor Sysoev为俄罗斯 ...