Ios5 development-http get/post call mvc4 webapi for interoperability (Image Upload)

Source: Internet
Author: User

Currently, the most popular cross-platform interaction is interoperation through JSON objects through http protocol. This method is simple and efficient. The WebService + XML method seems outdated.

The following is an example

Webapi code

View code

 
Public ienumerable <product> getallproducts ()
{
Console. writeline (datetime. Now. tolongtimestring () + ": receive request .");
Return new list <product>
{
New product () {id = 1, name = "Gizmo 1", price = 1.99 m },
New product () {id = 2, name = "Gizmo 2", price = 2.99 m },
New product () {id = 3, name = "Gizmo 3", price = 3.99 m },
New product () {id = 4, name = "Tshirt 3", price = 5.99 m },
New product () {id = 5, name = "soft Tshirt", price = 34.99 m },
};
}

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.99 m
};
}
// 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

// 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 = 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;

Ienumerable <product> or iqueryable <product> returned by webapi supports the odata protocol. The odata protocol has powerful functions and is easy to query. Follow up.

The first is to obtain and update server data through http get/post.

 

 

Code to get data code

-(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 initialize mselecw.mainthread: @ selector (setrespondtext :) withobject: jsonstring waituntildone: Yes modes: Nil];
[Self defined mselecw.mainthread: @ selector (setrespondtext :) withobject: Data waituntildone: No];
}
}
];

}

The post data code is as follows:

 

-(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 initialize mselecw.mainthread: @ selector (setrespondtext :) withobject: jsonstring waituntildone: Yes modes: Nil];
[Self defined mselecw.mainthread: @ selector (setrespondtext :) withobject: Data waituntildone: No];
}
}
];

}

Parses the obtained JSON string

-(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];

}

 

 

Image Upload code

 

-(Ibaction) uploadaction :( ID) sender {
Nsstring * urlstring = self. urltextfield. text;
// Nsstring * poststr = @"";
Nsdata * imgdata = uiimagejpegrepresentation (self. previewimageview. Image, 0.9f );

Nsstring * boundary = @ "0 xkhtmlboundary ";
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"] 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 initialize mselecw.mainthread: @ selector (setrespondtext :) withobject: jsonstring waituntildone: Yes modes: Nil];
// [Self initialize mselecw.mainthread: @ selector (setrespondtext :) withobject: Data waituntildone: No];
}
}
];

}

 

I feel that the nsmutableurlrequest, nsurlconnection, and nsjsonserialization that comes with the IOS SDK are also very convenient. It seems that there is no need to use a third-party class library.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.