在iOS中调用restful web服务

时间:2012-12-26 16:22:29

标签: web-services

我从iOS调用web API,我调用方法POST,我不能在post方法中传递参数

Web API:

public class Person
{
    public int Id { get; set; }
    public String Name { get; set; }
}

 // POST api/values
public void Post([FromBody]Person value)
{

}
iOS中的

NSURL *url =[NSURL URLWithString:@"http://localhost:9281/api/values"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
[theRequest setHTTPMethod:@"POST"];

NSURLConnection *theConnection = [[NSURLConnection alloc]initWithRequest:theRequest delegate:self];

如何在POST方法中传递值参数Person?

1 个答案:

答案 0 :(得分:2)

NSMutableURLRequest *request = [NSMutableURLRequest 
                                    requestWithURL:[NSURL URLWithString:@"http://www.domain.com/your/servlet"]];

NSString *params = [[NSString alloc] initWithFormat:@"foo=bar&key=value"];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];

这是来自此博文:http://www.deanoj.co.uk/ios-development/making-a-http-post-request-with-nsurlconnection/