I need to create request manually, not using AFNetworking.
NSString *baseURL = #"http://pl-dev2.railwaymen.org:4213/";
NSString *URLString = [NSString stringWithFormat:#"events/%#", identifier];
NSURL *url = [NSURL URLWithString:URLString relativeToURL:baseURL];
//final URL: http://pl-dev2.railwaymen.org:4213/events/6572673456
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"PUT"];
Now I want to send some parameters:
NSDictionary *params = #{
"a": "valueA",
"b": 23,
"c": [NSNull null],
"d": ["lisbona", "warsaw", "ny"],
"e": UIImageJPEGRepresentation(image, 1)
};
How do I do that?
NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:nil error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
[request setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
Unfortunately it doesnt work
How looks the final request URL?
http://pl-dev2.railwaymen.org:4213/events/6572673456?a=valueA&b=23&c=&d[]=lisbona&d[]=warsaw&d[]=ny&e=
Which part of that query is httpBody? Every after ?.
What about parameters c and e?
How it works?
Related
I tired picker view with array of four element from url link "branch_name"
(1) with button action.
Button action:
- (IBAction)picker_button:(id)sender {
NSString *parseURL =#"url(1)";
NSString *encodeurl =[parseURL stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:encodeurl];
NSData *data = [NSData dataWithContentsOfURL:url];
if(data){
NSError *error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options: kNilOptions error:&error];
arrMsg = [json valueForKeyPath:#"Branches.branch_name"];
NSLog(#"%#",json);
arrmsg1 =[json valueForKeyPath:#"Branches.id"];
[_pickerdata1 reloadAllComponents];
}
}
Then I used url link(2) passing parameter using POST NSURLConnection and successfully displayed in tableview.
Post method coding:
here i am passing parameter as Branchid=#"1" only but i want to pass parameter as entire branchid value. help me
-(void) sendDataToServer : (NSString *) method{
NSString *Branchid =#"1" ;
NSURL *url = nil;
NSMutableURLRequest *request = nil;
if([method isEqualToString:#"GET"]){
NSString *getURL = [NSString stringWithFormat:#"%#?branch_id=%#", URL, Branchid];
url = [NSURL URLWithString: getURL];
request = [NSMutableURLRequest requestWithURL:url];
NSLog(#"%#",getURL);
}else{ // POST
NSString *parameter = [NSString stringWithFormat:#"branch_id=%#",Branchid];
NSData *parameterData = [parameter dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
url = [NSURL URLWithString: URL];
NSLog(#"%#", parameterData);
request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPBody:parameterData];
arr= [NSMutableString stringWithUTF8String:[parameterData bytes]];
}
[request setHTTPMethod:method];
[request addValue: #"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if( connection )
{
mutableData = [NSMutableData new];
}
}
connection did finish loading:
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError* error;
json = [NSJSONSerialization JSONObjectWithData: mutableData
options:kNilOptions
error:&error];
NSLog(#"%#",json);
sellArray = [json valueForKeyPath:#"BranchByList.sell"];
buyArray = [json valueForKeyPath:#"BranchByList.buy"];
updataedArray = [json valueForKeyPath:#"BranchByList.updated"];
imageArray = [json valueForKeyPath:#"BranchByList.flag_image"];
currency =[json valueForKeyPath:#"BranchByList.currency"];
[ _dataview reloadData];
}
I have been trying to implement the Wego flights API from http://support.wan.travel/hc/en-us/articles/200191669 which uses HTTP POST requests. I've only really ever used GET requests, so I did some reading on POST and so far I have not been able to find a way to post a request with a dictionary of flight data (in objective-c) as shown in the link above:
POST api.wego.com/flights/api/k/2/searches
{
"trips": [
{
"departure_code": "SYD",
"arrival_code": "LON",
"outbound_date": "2014-01-24",
"inbound_date": "2014-01-29"
}
],
"adults_count": 1
}
Do I have to create the NSDictionary myself and then (assign?) it to the request, or is there a way to format the dictionary into a string? Thanks in advance for any help :)
You have to create the POST data as follows:
NSDictionary *trips = [NSDictionary dictionaryWithObjectsAndKeys:
#"SYD", #"departure_code",
#"LON", #"arrival_code",
#"2014-01-24", #"outbound_date",
#"2014-01-29", #"inbound_date",
nil];
NSDictionary *postDict = [NSDictionary dictionaryWithObjectsAndKeys:
trips, #"trips",
#"1", #"adults_count",
nil];
NSError *jsonError = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:postDict options:NSJSONWritingPrettyPrinted error:&jsonError];
And then make the POST request:
NSURL *url = [[NSURL alloc] initWithString:#"http://api.wego.com/flights/api/k/2/searches"];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:15];
[urlRequest setHTTPMethod:#"POST"];
const char *parameters = [jsonData bytes];
NSData *postData = [[NSData alloc] initWithBytes:parameters length:strlen(parameters)];
[urlRequest setHTTPBody:postData];
NSURLResponse *response = nil;
NSError *requestError = nil;
NSData * data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&requestError];
NSLog(#"%#", [NSString stringWithUTF8String:[data bytes]]);
I need to do this GET request:
http://api.testmy.co.il/api/sync?BID=1049&ClientCode=3847&Discount=2.34&Service=0&Items=[{"Name":"Tax","Price":"2.11","Quantity":"1","SerialID":"1","Remarks":"","Toppings":""}]&Payments=[]
In browser I get this response:
{
"Success": true,
"Atava": [],
"Pending": [],
"CallWaiter": false
}
But in iOS its not working.
I try:
NSString *requestedURL=[NSString stringWithFormat:#"http://api.testmy.co.il/api/sync?BID=%i&ClientCode=%i&Discount=2.34&Service=0&Items=[{\"Name\":\"Tax\",\"Price\":\"2.11\",\"Quantity\":\"1\",\"SerialID\":\"1\",\"Remarks\":\"\",\"Toppings\":\"\"}]&Payments=[]",BID,num];
NSURL *url = [NSURL URLWithString:requestedURL];
NSURLResponse *response;
NSData *GETReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
NSString *theReply = [[NSString alloc] initWithBytes:[GETReply bytes] length:[GETReply length] encoding: NSASCIIStringEncoding];
NSLog(#"Reply: %#", theReply);
OR
NSString *requestedURL = [NSString stringWithFormat:#"http://api.testmy.co.il/api/sync?BID=%i&ClientCode=%i&Discount=2.34&Service=0&Items=[{'Name':'Tax','Price':'2.11','Quantity':'1','SerialID':'1','Remarks':'','Toppings':''}]&Payments=[]", BID, num];
OR
NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
[params setObject:#"Tax" forKey:#"Name"];
[params setObject:#"2.11" forKey:#"Price"];
[params setObject:#"1" forKey:#"Quantity"];
[params setObject:#"1" forKey:#"SerialID"];
[params setObject:#"" forKey:#"Remarks"];
[params setObject:#"" forKey:#"Toppings"];
NSData *jsonData = nil;
NSString *jsonString = nil;
if([NSJSONSerialization isValidJSONObject:params])
{
jsonData = [NSJSONSerialization dataWithJSONObject:params options:0 error:nil];
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"%#", jsonString);
}
NSString *get = [NSString stringWithFormat:#"&Items=%#", jsonString];
NSData *getData = [get dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setHTTPMethod:#"GET"];
[request setTimeoutInterval:8];
[request setHTTPBody:getData];
[request setValue:#"application/json;charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
I tried all above code but it doesn't work(long time out.. just stuck on this).How to fixing this?
This is because your URL is not correct, this string should add percent escape. Try with this:
NSString *requestedURL=[NSString stringWithFormat:#"http://api.testmy.co.il/api/sync?BID=%i&ClientCode=%i&Discount=2.34&Service=0&Items=[{'Name':'Tax','Price':'2.11','Quantity':'1','SerialID':'1','Remarks':'','Toppings':''}]&Payments=[]",BID,num];
NSURL *url = [NSURL URLWithString:[requestedURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
//and you use this url
// Send a synchronous request
NSURLRequest * urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:#"enter your url here"]];
NSURLResponse * response = nil;
NSError * error = nil;
NSData * data = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:&error];
if (error == nil)
{
// Parse data here
}
The NSURLResponse and NSError vars are passed into the sendSynchronousReqeust method so when it returns, they will be populated with the raw response and error (if any). If you need to check for stuff like response codes you can do so via the “response” variable you pass.
I want to reach from ios to a .net .asmx web service, and I reach with the following code:
NSString *urlString = #"http://www.****.com/Mobile.asmx/HelloWorld";
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod: #"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSError *errorReturned = nil;
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&errorReturned];
if (errorReturned)
{
//...handle the error
}
else
{
NSString *retVal = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"%#", retVal);
//...do something with the returned value
}
It returns clean json {"hellom":"Hello World","hellom2":"HelloWorld2"} but I can't reach members and value one by one
How can I do that?
You can convert JSON data into an object by using the following code...
NSData *jsonData = ... the data you got from the server
NSDictionary *object = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
object will then be a NSDictionary like this...
#{
hellom : #"Hello World",
hellom2: #"HelloWorld2"
}
You can then get to the keys and values like any other dictionary.
I am trying to build an app with a map in which the user would select his origin address and destination address.. It all works fine, but I can't access the Google API Distance Matrix..
I am try with following:
NSString *urlPath = [NSString stringWithFormat:#"/maps/api/distancematrix/xml?origins=%#=%#&mode=driving&language=en-EN&sensor=false" ,polazisteField.text , odredisteField.text];
NSURL *url = [[NSURL alloc]initWithScheme:#"http" host:#"maps.googleapis.com" path:urlPath];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc]init]autorelease];
[request setURL:url];
[request setHTTPMethod:#"GET"];
NSURLResponse *response ;
NSError *error;
NSData *data;
data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *result = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
address.text = result;
, but have no luck, any idea how to resolve this?
I think your call has been considred as invalid API call.
try below code that is edited from your code snippet.
NSString *urlPath = [NSString stringWithFormat:#"/maps/api/distancematrix/json?origins=%#&destinations=%#&mode=driving&language=en-EN&sensor=false" ,polazisteField.text , odredisteField.text];
NSURL *url = [[NSURL alloc]initWithScheme:#"http" host:#"maps.googleapis.com" path:urlPath];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:url];
[request setHTTPMethod:#"GET"];
NSURLResponse *response ;
NSError *error;
NSData *data;
data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSMutableDictionary *jsonDict= (NSMutableDictionary*)[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSMutableDictionary *newdict=[jsonDict valueForKey:#"rows"];
NSArray *elementsArr=[newdict valueForKey:#"elements"];
NSArray *arr=[elementsArr objectAtIndex:0];
NSDictionary *dict=[arr objectAtIndex:0];
NSMutableDictionary *distanceDict=[dict valueForKey:#"distance"];
NSLog(#"distance:%#",[distanceDict valueForKey:#"text"]);
NSString *result = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
address.text = [distanceDict valueForKey:#"text"];