发布数据并获得成功的响应

时间:2013-04-05 10:05:53

标签: ios objective-c http-post nsurlconnection

嗨,我是iphone开发新手可以解释一下 如何将数据发布到URL并从中获得成功的响应 下面是示例代码...

-(IBAction)clicked:(id)sender{
    NSString *CIDString = cID.text;

    NSURL *url = [NSURL URLWithString:@"http://localhost:8080/test/?"];
    NSString *postData = [NSString stringWithFormat:@"companyID=%@",CIDString];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[url standardizedURL]
                                                           cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];

    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:[postData dataUsingEncoding:NSUTF8StringEncoding]];

    [self startConnection:(NSMutableURLRequest *)request];
     if([self.result isEqualToString:@"New Alert"])
    {
        cID.text = @"Scuess";
    }

}

和startConnection如下

- (void)startConnection:(NSMutableURLRequest *)request {

    [self.connection cancel];

    NSMutableData *data = [[NSMutableData alloc] init];
    self.receivedData = data;
    self.result = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
    NSLog(@"receivedData: %@", [[NSString alloc] initWithData:receivedData encoding:NSASCIIStringEncoding]);


    self.connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

    if (self.networkErrorAlert) {
        NSLog(@"connection fail");

    }

    [self.connection start];
}

有人可以帮助我......

1 个答案:

答案 0 :(得分:0)

- (void)sendrequest {

NSString *tempusername = txtusername.text;
NSString *tmppassword = txtpassword.text;
NSString *tempurllogin = [staticstrings URLLink];
NSString *tmpURL = [NSString stringWithFormat:@"http://example.com/ValidateService?", tempurllogin];
NSString *connect;
connect = [NSString stringWithFormat:@"%@emailAddress=%@&password=%@", tmpURL,tempusername,tmppassword];

responseData = [[NSMutableData data] retain];
NSURL *url = [[NSURL alloc] initWithString:connect];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[[NSURLConnection alloc] initWithRequest:request delegate:self];

[url release];
[request release];

}