How can i send my data to server through URL.[iOS] [duplicate] - ios

This question already has answers here:
Sending an HTTP POST request on iOS
(7 answers)
Closed 8 years ago.
How can i send data to server through URL using POST method.
My data is like below:
json == {
Signup = {
email = test;
password = 123;
username = test;
};
}
My URL is like this:
http://192.168.1.122/~test/sample/index.php/Api/signup
Please suggest me. I am stuck on this from last 2 days. Please help me.
Data format is JSON.

You could do something similar to send a simple post request with JSON Data
-(void)sendPostData{
NSString *urlStr = #"http://me.com";
urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:urlStr];
NSDictionary* info = [NSDictionary dictionaryWithObjectsAndKeys:user.userName,#"username",user.password,#"password",user.email,#"email", nil];
NSError *error;
NSData* bodyData = [NSJSONSerialization dataWithJSONObject:info
options:kNilOptions error:&error];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:data];
[request setValue:[NSString stringWithFormat:#"%d", [data length]] forHTTPHeaderField:#"Content-Length"];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *responseFromRequest, NSData *data, NSError *error)
{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)responseFromRequest;
NSInteger code = [httpResponse statusCode];
}];
}

Have a look at my GitHub repo JWURLConnectionenter link description here, this will help you.
If you'r targeting an API I would also recommend JWRESTClient.

Related

how to send the values in body when I call the asynchronous post request

I am trying to do a task which I am completely not aware of, that is video uploading to server in objective c. I am a beginner and I was using swift, but now my requirement is in objective c.
Here I have to send an asynchronous request using multipart form data to server with three values. here is the data need to send in body:
body->form-data
projectId : String
sessionId : String
file : file
Its getting crashed at this line
" [urlRequest addValue:#"65" forHTTPHeaderField:#"projectId"];"
Can anyone help me to do this.
Thanks in advance.
NSString *str = [NSString stringWithFormat:#"http://abcdefghijkl.mnopqrst.com:8965/upload"];
NSURL *url = [NSURL URLWithString:str];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
[urlRequest addValue:#"65" forHTTPHeaderField:#"projectId"];
[urlRequest addValue:#"43" forHTTPHeaderField:#"sessionId"];
[urlRequest addValue:#"" forHTTPHeaderField:#"file"];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (error) {
NSLog(#"Error,%#", [error localizedDescription]);
} else {
NSLog(#"%#", [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]);
}
}];
You should use NSMutableURLRequest
NSMutableURLRequest is a subclass of NSURLRequest that allows you to
change the request’s properties.
NSMutableURLRequest *mutableRequest = [request mutableCopy];
[mutableRequest addValue:#"65" forHTTPHeaderField:#"projectId"];
...
request = [mutableRequest copy];

Unsupported URL when sending Json value as argument in GET method

Code:
arrValues = [[NSMutableArray alloc]initWithObjects:#"Chennai", nil];
arrKeys = [[NSMutableArray alloc]initWithObjects:#"loc", nil];
dicValue = [NSDictionary dictionaryWithObjects:arrValues forKeys:arrKeys];
NSString *strMethodName = #"agentuserlist";
strUrlName = [NSString stringWithFormat:#"%#%#?filters=%#",appDelegate.strURL, strMethodName, dicValue];
//strUrlName = [strUrlName stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:strUrlName] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:250.0];
[request setHTTPMethod:#"GET"];
[request setHTTPShouldHandleCookies:YES];
[request setValue:#"zyt45HuJ70oPpWl7" forHTTPHeaderField:#"Authorization"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
NSError *error;
NSURLResponse *response;
NSData *received = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response error:&error];
NSLog(#"error:%#", error);
NSString *strResponse = [[NSString alloc]initWithData:received encoding:NSUTF8StringEncoding];
NSLog(#"response :%#", strResponse);
I try to send json argument through get method.It gives error as "unsupported url(-1002)".
The URL is working fine when I checked with Postman. I am unable to find out the problem.
Where I went wrong?
I think the problem lies in how you encode your NSDictionary in the NSURL.
You probably want your URL to look like this: http://my domain.com/agentuserlist?loc=Chennai. But the raw encoding of the NSDictionary inside the NSURL doesn't produce this result.
You can follow the accepted answer
from this question to get an idea of how to transform an NSDictionary into a regular list of URL parameters (with proper encoding of dictionary values: don't forget the stringByAddingPercentEscapeUsingEncoding part): Creating URL query parameters from NSDictionary objects in ObjectiveC

Difficulty receiving JSON from GET request using NSURLConnection

I'm having a hard time trying to receive JSON form a NSURLConnection request. Can anybody offer any advice? I can't understand why the JSON does not appear
EDIT: When I append the endpoint /books to the end of the url string I get this JSON response: " json NSDictionary * 0 key/value pairs. " Does this mean that there is nothing in the server?
-(void)makeLibraryRequests
{
NSURL *url = [NSURL URLWithString:#"http://prolific-interview.herokuapp.com/54bexxxxxxxxxxxxxxxxaa56"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; //;]cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:20.0f];
[request setHTTPMethod:#"GET"];
// This is actually how jQuery works. If you don't tell it what to do with the result, it uses the Content-type to detect what to do with it.
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
//[request setValue:#"application/json; charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
//parse data here!!
NSError *jsonError;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonError];
if (json) {
//NSArray *allBooks = [json objectForKey:#"books"];
//create your MutableArray here
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
}
else{
NSLog(#"error occured %#", jsonError);
NSString *serverResponse = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"\n\nError:\n%#\n\nServer Response:\n%#\n\nCrash:", jsonError.description, serverResponse);
//[NSException raise:#"Invalid Data" format:#"Unable to process web server response."];
}
}];
}
As YiPing pointed out, you must provide the books end point. But you won't have anything there until you first post a book.
NSDictionary *params = #{#"author": #"Diego Torres Milano",
#"categories" : #"android,testing",
#"title": #"Android Application Testing Guide",
#"publisher": #"Packt Publishing",
#"lastCheckedOutBy": #"Joe"};
NSURL *url = [NSURL URLWithString:#"http://prolific-interview.herokuapp.com/54bexxxxxxxxxxxxxaa56/books/"]; // your id removed for security's sake ... put it back in
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSError *encodeError;
NSData *body = [NSJSONSerialization dataWithJSONObject:params options:0 error:&encodeError];
NSAssert(body, #"JSON encode failed: %#", encodeError);
request.HTTPBody = body;
So, first POST a book using a request like the above, then your original GET (assuming you add the end point) will now return a result.
Add some endpoints to your URL
try this:
http://prolific-interview.herokuapp.com/54bexxxxxxxxxxxxxxxxaa56/books/

Making HTTP Requests API Calls

I have the following code in the IOS SDK I am building:
+ (void) makeRequestToEndPoint:(NSString *) endpoint values:(NSMutableDictionary *) params onCompletion:(SDKCompletionBlock) responseHandler
{
[params setObject: key forKey: #"key"];
NSString * urlString = [self createApiUrlFromEndpoint: endpoint];
NSURL * url = [NSURL URLWithString: urlString];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: url];
request.HTTPMethod = #"POST";
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"charset" forHTTPHeaderField:#"utf-8"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
request.HTTPBody = [[params urlEncodedString] dataUsingEncoding:NSUTF8StringEncoding];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
NSError * dicError = nil;
NSDictionary * dictionary = nil;
if([data length] >= 1) {
dictionary = [NSJSONSerialization JSONObjectWithData: data options:kNilOptions error: &dicError];
}
responseHandler(dictionary, error);
}];
}
So that people using the SDK can make API calls by doing the following:
[SDK makeRequestToEndpoint: #]
What is the best way to structure (best way to handle error handling, response handling, etc) the code above to make easy for people to use the SDK?
There are many open source frameworks from which you can learn good design practices for asynchronous networking. I recommend you take a look at
AFNetworking

NSURLConnection sends GET request instead of POST request

I'm trying to make a POST request using NSURLConnection. I use Charles to debug and Charles every time says that the method is GET. I've tried all different ways and can't get it to work. I am NOT using JSON.
-(void)getList
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSURL *url = [NSURL URLWithString:#"http://example.com/api/getList"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSString *radius = #"15";
NSString *latitude = #"-117.820833";
NSString *longitude = #"34.001667";
NSString *parameters = [NSString stringWithFormat:#"longitude=%#&latitude=%#&radius=%#", longitude,latitude, radius];
NSLog(#"PARAMS = %#", parameters);
NSData *data = [parameters dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:#"POST"];
[request setValue:#"text/plain" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:data];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *responseString = [[NSString alloc]initWithData:result encoding:NSUTF8StringEncoding];
NSLog(#"RESULT = %#", responseString);
}
Does anybody know what am I doing wrong? When I access my web service it seems like I'm not posting anything. I'm getting empty response.
Please help with any ideas. I pretty much have to make a simple POST request. Maybe someone can help me debug this better.
If the server is redirecting your request for some reason (perhaps authentication) then the POST information can get lost.

Resources