POST提交数据并获取返回值(XML格式的字符串)

@try {
        NSError *error;
        NSURL *url = [NSURL URLWithString:@"http://www.corp.com/info.xml"];

        NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
        
        [dic setValue:@"14" forKey:@"type"];
        [dic setValue:@"POST" forKey:@"method"];
        [dic setValue:@"1" forKey:@"siteid"];
         
        NSString *myBounds = [[NSString alloc] initWithString:@"test"];
        NSMutableURLRequest *myRequest = [NSMutableURLRequest requestWithURL:url];
        NSString *myContent = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",myBounds];
        [myRequest setValue:myContent forHTTPHeaderField:@"content-type"];
        [myRequest setHTTPMethod:@"POST"];
        [myRequest setHTTPBody:[self createFormData:dic withBoundary:myBounds]];
        
        NSURLResponse *response;
        NSData *myReturn = [NSURLConnection sendSynchronousRequest:myRequest returningResponse:&response error:&error];
        
        NSString *str = [[NSString alloc] initWithData:myReturn encoding:NSUTF8StringEncoding];
    }
    @catch (NSException *exception) {
        //
    }
    @finally {
        //
    }


- (NSData*)createFormData:(NSDictionary *)myDictionary withBoundary:(NSString *)myBounds{
    NSMutableData *myReturn = [[NSMutableData alloc] initWithCapacity:10];
    NSArray *formKeys = [myDictionary allKeys];
    
    for(int i=0;i<[formKeys count];i++){
        [myReturn appendData:[[NSString stringWithFormat:@"--%@\n",myBounds] dataUsingEncoding:NSUTF8StringEncoding]];
        [myReturn appendData:[[NSString stringWithFormat:@"content-disposition: form-data; name=\"%@\"\n\n%@\n", [formKeys objectAtIndex:i], [myDictionary valueForKey:[formKeys objectAtIndex:i]]] dataUsingEncoding:NSUTF8StringEncoding]];
    }
    
    [myReturn appendData:[[NSString stringWithFormat:@"--%@--\n", myBounds] dataUsingEncoding:NSUTF8StringEncoding]];
    return myReturn;
}


你可能感兴趣的:(Apple开发)