0

我正在使用 webservie 发布数据,但数据没有发布到数据库中。`

    NSURL *url = [NSURL URLWithString:@"some url"];
    NSArray *res=[[NSArray alloc] initWithObjects:txtname.text, nil];
    NSError *jsonError;
    //NSJSONSerialization is Apple's new json serialization class so we can use it to convert to and from json and foundation objects
    NSData *requestdata = [NSJSONSerialization dataWithJSONObject:res options:0 error:&jsonError];


    NSMutableURLRequest *request;
    request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    [request setValue:[NSString stringWithFormat:@"%d", [requestdata length]] forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:requestdata];

    //this kicks off the request asynchronously
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

`
4

1 回答 1

0
NSString *parameter1=@"";
NSString *parameter2=@"";  

NSString *urlString = [NSString stringWithFormat:@"your URL"];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];

NSMutableData *body = [NSMutableData data];

NSString *boundary = @"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];

//  parameter parameter1
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"parameter_1\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:parameter1
 dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

//  parameter parameter2
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"parameter_2\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:parameter2 dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

// close form
[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];


// setting the body of the post to the reqeust
[request setHTTPBody:body];

// now lets make the connection to the web
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];

NSLog(@"returnString %@",returnString);

以类似的方式,您可以根据需要添加任意数量的参数。

于 2013-04-19T05:47:30.740 回答