unsupported URL error code -1002

Enmud picture Enmud · Feb 19, 2014 · Viewed 10.3k times · Source

Hi Please help me how to prepare NSMutableURLRequest for below api

URL : www.XXXXXXXX.com/api.php

For Login :-

www.XXXXXXXXXXXX.com/api.php?task=login

POST Data :-

"email" => User's email

"pw" => User's Password

json response: session id on successful login

Am trying like this.

NSMutableURLRequest *request;

request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"www.XXXXXXXX.com/api.php?task=login"]];


[request setHTTPMethod:@"POST"];


NSString *postString =@"[email protected]&pw=1234";

[request setValue:[NSString
                   stringWithFormat:@"%d", [postString length]] forHTTPHeaderField:@"Content-length"];

[request setHTTPBody:[postString
                      dataUsingEncoding:NSUTF8StringEncoding]];

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

Answer

Martin R picture Martin R · Feb 19, 2014

One reason could be that you forgot to add the "http:" scheme:

[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.XXXXXXXX.com/api.php?task=login]];
                                                     HERE --^

Note also that the correct way to set body data and in particular the length is

NSString *postString =@"[email protected]&pw=1234";
NSData *postData = [postString dataUsingEncoding:NSUTF8StringEncoding];
[request setValue:[NSString stringWithFormat:@"%d", [postData length]]
              forHTTPHeaderField:@"Content-length"];
[request setHTTPBody:postData];

because the length of the UTF-8 encoded data can be different from the (Unicode) string length.