I'm trying to load a URL in NSMutableURLRequest for a GET request as below:
NSString *serverAddress = [NSString stringWithFormat:#"http://test.us.to:8080/api/offers?altId=%#&provider=%#&otherId=%#&tenantId=%#&createdAt=%#&otherOfferId=%#&postId=%#&pageId=%#&sourceUrl=%#&name=%#&description=%#&text=%#&category=%#&caption=%#&startTime=%#&expirationTime=%#&minPurchase=%#&numPurchases=%#&value=%#&percent=%#&count=%#¤cy=%#&terms=%#&campaignId=%#&partnerId=%#&tenantIdAtPartner=%#&issuerName=%#&claimLimit=%#&onePerUser=%#&emailTemplateFile=%#",#"test",#"Facebook",#"",#"test",#"null",#"test",#"",#"",#"http://test.us.to/offers/harvester_summer13.html",#"Harvester",#"Harvester 2for1 TakeAway",#"Enjoy!",#"voucher",#"Harvester 2for1 TakeAway",[NSNumber numberWithInt:0],#"test",[NSNumber numberWithInt:0],[NSNumber numberWithInt:0],#"1000",[NSNumber numberWithInt:0],[NSNumber numberWithInt:0],#"GBP",#"",[NSNumber numberWithInt:1259],#"null" ,#"null" ,#"null",[NSNumber numberWithInt:100],[NSNumber numberWithBool:false],#"templates/test.vm"];
NSURL *url = [NSURL URLWithString:[serverAddress urlEncodeUsingEncoding:NSUTF8StringEncoding]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadRevalidatingCacheData timeoutInterval:15.0];
NSString *authStr = [NSString stringWithFormat:#"%#:%#", #"testuser", #"testpwd"];
NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
NSString *authValue = [NSString stringWithFormat:#"Basic %#", [authData base64EncodedStringWithOptions:0]];
[request setValue:authValue forHTTPHeaderField:#"Authorization"];
[request setHTTPMethod: #"GET"];
NSError *requestError;
NSURLResponse *urlResponse = nil;
NSData *response1 = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&requestError];
NSLog(#"output data %#",response1);
I guess I'm loading way too many parameters using the url string. Is there a better way to pass parameters for a GET request ? The current output is null for response1
It looks to me like the issue is that you are encoding the whole url with some sort of encoding method, but you really just need to encode each parameter separately if it contains certain characters. For example:
NSString *serverAddress = #"http://test.us.to:8080/api/offers";
NSString *altIdParameter = [#"Escape?This?String?" urlEncodeUsingEncoding:NSUTF8StringEncoding];
NSString *aUrlParameter = [#"http://test.us.to/offers/harvester_summer13.html" urlEncodeUsingEncoding:NSUTF8StringEncoding];
NSString *getRequestUrl = [NSString stringWithFormat:%#?altId=%#&urlParam=%#", serverAddress, altIdParameter, aUrlParameter];
NSURL *url = [NSURL URLWithString:getRequestUrl];
Related
I am using two links.First link i created nsaaray for "id".This "id" i need to pass as parameter in nsurlconnection using POST method by second link.i tried lots but i stuck in while passing parameter "id".
nsaaray for id:
- (IBAction)button_drop:(id)sender {
NSString *parseURL =#"first_link";
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"];
arrmsg1 =[json valueForKeyPath:#"Branches.id"];
[_picker2 reloadAllComponents];
}
}
POST method using nsurlconnection:
NSString *Branchid=#"3";
NSURL *url = nil;
NSMutableURLRequest *request = nil;
if([method isEqualToString:#"GET"]){
NSString *getURL = [NSString stringWithFormat:#"%#?branch_id=%#\n", 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];
}
Try to create a "POST" method like this:-
NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:
Branchid, #"branch_id", nil];
NSString *newRequest = [dict JSONRepresentation];
NSData *requestData = [newRequest dataUsingEncoding:NSUTF8StringEncoding];
//If you are not using SBJsonParser Library then try the following:
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *urlString = #"YOUR URL String";
NSURL *requestURL = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:requestURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long) [requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:requestData];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection) {
mutableData = [NSMutableData new];
}
Also, You can follow this link if you don't find out the answer working properly:-
Data in POST or GET methods
Send data in POST methods
I am trying to parse data for google translate. In viewdidload, I wrote the following code.
NSString * target = #"ja";
NSString * source = #"en";
NSString *textEscaped = #"Hi, How are u";
NSString *ke=#"My_key";
NSString * urlText =[NSString
key=%#&source=%#&format=text&target=%#&q=%#",ke,source,target,textEscaped];
NSURL *url = [NSURL URLWithString:urlText];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:url];
[request setHTTPMethod:#"GET"];
NSURLResponse *response;
NSError *error;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response
error:&error];
NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"%#",result);
I compared my code with different sources and my API is also activated but I am getting nothing in result string. Its bill. Why?
Create Your url like this:
[NSString stringWithFormat:#"https://www.googleapis.com/language/translate/v2key=%#&target=%#&q=%#",key, target, selectedWord];
Here I am trying to access the secured URL using the HTTP authentication. But still the data is coming null.
code:
{
NSURL *url = [NSURL URLWithString:#"http://mysecuredurl.com"];
NSString *userName =#"abc#v.com";
NSString *password =#"12345";
NSError *myError = nil;
NSMutableString *loginString = (NSMutableString*)[#"" stringByAppendingFormat:#"%#:%#", userName, password];
NSLog(#"loginstring=%#",loginString);
NSString *authHeader = [#"Basic " stringByAppendingFormat:#"%#", loginString];
NSLog(#"auth header =%#",authHeader);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: url
cachePolicy: NSURLRequestReloadIgnoringCacheData
timeoutInterval: 3];
NSLog(#"request %#",request);
[request addValue:authHeader forHTTPHeaderField:#"Authorization"];
NSURLResponse *response;
NSData *data = [NSURLConnection
sendSynchronousRequest: request
returningResponse: &response
error: &myError];
NSLog(#"data %#",data);
NSLog(#"response %#",response);
NSString *result = [[NSString alloc]initWithData:data
encoding:NSUTF8StringEncoding];
NSLog(#"result = %#",result);
}
Both data and response is null. Please do help me out in this. Is there any changes do I need to do? Thank you.
Your authentication string needs to be base64 encoded. Try -
NSData *userPasswordData = [[NSString stringWithFormat:#"%#:%#", userName, password] dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64EncodedCredential = [userPasswordData base64EncodedStringWithOptions:0];
NSString *authHeader= [NSString stringWithFormat:#"Basic %#", base64EncodedCredential]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: url
cachePolicy: NSURLRequestReloadIgnoringCacheData
timeoutInterval: 3];
[request addValue:authHeader forHTTPHeaderField:#"Authorization"];
Encoding:
NSData *imageData2 =UIImageJPEGRepresentation(image_emp.image, 0.1);
[Base64 initialize];
NSString *encodedString = [imageData2 base64EncodedStringWithOptions:0];
json:
NSString *posturl=[NSString stringWithFormat:#"http://xxxx.com/image.php?img=%#",encodedString];
//[posturl stringByReplacingOccurrencesOfString:#"+" withString:#"%2B"];
NSString* urlTextEscaped = [posturl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"replace log %#",urlTextEscaped);
[urlTextEscaped stringByReplacingOccurrencesOfString:#"+" withString:#"%2B"];
NSLog(#"the office login url is %#",posturl);
NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:#"%#",urlTextEscaped]];
// NSURL *url=[NSURL URLWithString:[posturl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSMutableURLRequest *request=[[NSMutableURLRequest alloc]init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSError *error;
NSURLResponse *response;
NSData *urldata=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *data=[[NSString alloc]initWithData:urldata encoding:NSUTF8StringEncoding];
NSLog(#"the overall value is %#",data);
NSDictionary *results=[data JSONValue];
NSLog(#"the results:%#",results);
NSArray *value=[results objectForKey:#"message"];
NSLog(#"the array value %#",value);
array value[log]:
Request-URI Too Large
How can I solve this type of issue.Kindly give any ideas.Thanks in Advance.
Don't POST the data in the URL, take advantage of the post body and submit it there. It's the only way to get a lengthy amount of data submitted.
In calling apexrest webservice for uploading attachment to specific record by calling method. So for this I hardcoded Json.
-(void)uploadToSalesforce
{
NSData *imagedata = UIImageJPEGRepresentation(imagePreview.image, 1.0);
int datalength = [imagedata length];
NSString *filename = [NSString stringWithFormat:#"Supload_iPhone_%d.jpg",datalength];
NSString *req = [NSString stringWithFormat:#"{\n\"name\":\"%#\",\n\"Body\": \"%#\"\n,\"ParenId\":%#\"\n}",filename,imagedata,receivedrecordid];
const char *utfString = [req UTF8String];
NSData *postData = [NSData dataWithBytes:utfString length:strlen(utfString)];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *requestUrl = [[NSMutableURLRequest alloc] init ];
[requestUrl setURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#/services/apexrest/Account/",receivedinstanceurl]]];
[requestUrl setHTTPMethod:#"POST"];
[requestUrl setValue:postLength forHTTPHeaderField:#"Content-length"];
[requestUrl setValue:[NSString stringWithFormat:#"Bearer %#",receivedaccesstoken] forHTTPHeaderField:#"Authorization"];
[requestUrl setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[requestUrl setHTTPBody:postData];
NSURLResponse *response;
NSError *err;
NSData *reponseData = [NSURLConnection sendSynchronousRequest:requestUrl returningResponse:&response error:&err];
NSString *res = [[NSString alloc] initWithData:reponseData encoding:NSASCIIStringEncoding];
}
In response it says there is
[{"message":"Unexpected parameter encountered during deserialization: Name at [line:2, column:9]","errorCode":"JSON_PARSER_ERROR"}]
In console JSON seems correct but cannot parse parameter "Name".I think this is not by IOS code. Or is there some different format.
In the line
NSString *req = [NSString stringWithFormat:#"{\n\"name\":\"%#\",\n\"Body\": \"%#\"\n,\"ParenId\":%#\"\n}",filename,imagedata,receivedrecordid];
JSON is missing " character for ParentId key value. It should be:
NSString *req = [NSString stringWithFormat:#"{\n\"name\":\"%#\",\n\"Body\": \"%#\"\n,\"ParenId\":\"%#\"\n}",filename,imagedata,receivedrecordid];
Therefore Salesforce webservice deserialization was throwing exception.