BlueSky
BlueSky

Reputation: 139

IOS - Format Url send to Server

I have a format url like this:

NSString *url1 = [NSString stringWithFormat:@"%@",http:abc.com/check?para1= 1,2,3,4,5,6,7,8...,1000&Param2= 1,2,3...,1000&Param3=12:12:12.000&Param4=1.12310&Param5=http:yahoo.com/adsf.html]

Im using

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url1]];
    [request setHTTPMethod:@"POST"];
    [request setValue:[NSString stringWithFormat:@"%d", [url1 length]] forHTTPHeaderField:@"Content-length"];
    [request setValue:@"text/plain" forHTTPHeaderField:@"Content-type"];

    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [NSURLConnection connectionWithRequest:request delegate:self];
    
    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSString *responseString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
    NSLog(@"response - %@",responseString);

but I can't send to server.

Upvotes: 0

Views: 728

Answers (2)

Kuo Ming Lin
Kuo Ming Lin

Reputation: 143

I modified your code, please try this :

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSString *url1       = [NSString stringWithFormat:@"%@", @"para1= 1,2,3,4,5,6,7,8...,1000&Param2= 1,2,3...,1000&Param3=12:12:12.000&Param4=1.12310&Param5=http:yahoo.com/adsf.html"];
NSData *postData     = [url1 dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];    
NSString *postLength = [NSString stringWithFormat:@"%u", [postData length]];
[request setURL:[NSURL URLWithString:@"http:abc.com/check"]];
[request setHTTPMethod:@"POST"];
[request setValue:@"Close" forHTTPHeaderField:@"Connection"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"text/plain" forHTTPHeaderField:@"Content-type"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];    
NSData *returnData       = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *responseString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(@"response - %@",responseString);

May it can help you.

Upvotes: 1

Daij-Djan
Daij-Djan

Reputation: 50129

I suspect you're doing it wrong and try put the POST body into the URL.

I deduce that from the way you try to set content-length based on url length.

The post body needs to be the content with request.HTTPBody = dataToPost

the url can't be that long then.


I'd advise to read up on the difference between GET and POST

refer to this question to see how to POST data

How send NSData using POST from a iOS application?

Upvotes: 0

Related Questions