简体   繁体   中英

iPhone : How to fetch data from web service where web service uses “POST” method for JSON?

I want to fetch data from web service using JSON in my app.

Web service is developed in C# and it uses POST method to pass data.

I found one example but its useful only for GET method?

So How can I fetch JSON data where web service uses POST method?

And I also want to send data to web service. How can I do that ?

I'm sending POST request in following way (sending xml with some parameters).

    NSString *message = [[NSString alloc] initWithFormat:@"<?xml version=\"1.0\" ?>\n<parameters></parameters>"];

    NSURL *url = [NSURL URLWithString:@"https://www.site.com"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    NSString *msgLength = [NSString stringWithFormat:@"%d",[message length]];

    [request addValue:@"application/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [request addValue:msgLength                         forHTTPHeaderField:@"Content-Length"];

    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:[message dataUsingEncoding:NSUTF8StringEncoding]];
    [message release];

    self.connection = [NSURLConnection connectionWithRequest:request delegate:self];

To collect data you should implement method:

    - (void)connection:(NSURLConnection *)conn didReceiveData:(NSData *)data

where you should save received data.

In method:

    - (void)connectionDidFinishLoading:(NSURLConnection *)conn

you can parse that data with some JSON -parser.

Hope, that will help you. If you'll have questions about this code ask them in comments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM