I'm getting error Request failed: bad request (400) while trying to post in LInkedIn
Below is my code
-(IBAction)btnLinkedIdShareClicked:(id)sender{
NSString *stringRequest = [NSString stringWithFormat:#"https://api.linkedin.com/v1/people/~/shares?oauth2_access_token=%#&format=json",[[NSUserDefaults standardUserDefaults] valueForKey:LINKED_IN_ACCESS_TOKEN]];
//Request parameter on a dictionary (keys in camel case)
NSDictionary *update = [[NSDictionary alloc] initWithObjectsAndKeys:[[NSDictionary alloc] initWithObjectsAndKeys: #"anyone",#"code",nil], #"visibility",
#"TEST", #"comment",[[NSDictionary alloc] initWithObjectsAndKeys:#"description share", #"description", #"link_url", #"submittedUrl", #"title share",#"title", #"image_url",#"submittedImageUrl",nil], #"content",nil];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
AFJSONRequestSerializer *requestSerializer = [AFJSONRequestSerializer serializer];
[requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Accept"];
manager.requestSerializer = requestSerializer;
[manager POST:stringRequest parameters:update success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"result: %#", responseObject);
//completionBlock(YES, responseObject, nil);
NSLog(#"Yes");
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"%#",[error localizedDescription]);
NSLog(#"No");
}];
}
Thanks in advance, any solution to resolve this...?
Related
I'm using AFNetworking to post data into the web. The information I have is the URI which is baseURL/post_user_info and they want input as A JSON object containing each of the name-value pairs. In the code written below I've set the name-value pair in a dictionary. My question is how to make it's json and send it as input value?
NSString *string = [NSString stringWithFormat:#"%#?post_user_info",BaseURLString];
NSString *escapedPath = [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
NSDictionary *params = #{#"input_1": #"hello world",
#"input_2": #"my#you.com",
#"input_3": #"newworldorder"};
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:params options:kNilOptions error:nil];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPBody:jsonData];
[manager POST:escapedPath parameters:[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding] progress:nil success:^(NSURLSessionTask *task, id responseObject)
{
NSLog(#"%#",responseObject);
}failure:^(NSURLSessionTask *operation, NSError *error)
{
NSLog(#"%#",[error localizedDescription]);
}];
I've updated the code because now I have generated the JSON but if I run the code now it give me Error: 400 which means If input_values is empty, a bad request error will be output.
#interface AFJSONRequestSerializer : AFHTTPRequestSerializer
AFJSONRequestSerializeris a subclass ofAFHTTPRequestSerializerthat encodes parameters as JSON using NSJSONSerialization.
add this AFJSONRequestSerializer is used for send JSON not a Raw Data add this and try once
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
e.g
NSString *string = [NSString stringWithFormat:#"%#?post_user_info",BaseURLString];
NSString *escapedPath = [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
/************** karthik Code added ******************/
AFHTTPSessionManager* manager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
/************** karthik Code added ******************/
NSDictionary *params = #{#"1": #"hello world",
#"2": #"my#you.com",
#"3": #"newworldorder"};
[manager POST:escapedPath parameters:params progress:nil success:^(NSURLSessionTask *task, id responseObject)
{
NSLog(#"%#",responseObject);
NSError *error = nil;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
NSLog(#"json == %#", json);
} failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(#"%#", [error localizedDescription]);
}];
Update Params
NSDictionary *params = #{#"1": #"hello world",
#"2": #"my#you.com",
#"3": #"newworldorder"};
NSMutableDictionary *modify = [NSMutableDictionary new];
[modify setObject:params forKey:#"input_values"];
you get output of
Im using salesforce live agent rest api in ios app, trying to request chat but always fail with 400 request is not a valid ChasitorInit
NSDictionary *parameters =#{ #"SessionId" :self.sessionId,
#"OrganizationId" :ORG_ID,
#"deploymentId" :DEPLOYEMENT_ID,
#"buttonId" :BUTTON_ID,
#"userAgent" :USER_AGENT,
#"language" :LANG,
#"screenResolution" :SCREEN_RES,
#"visitorName" :#"Test Visitor",
#"prechatDetails" :#[],
#"prechatEntities" :#[],
#"receiveQueueUpdates":#"true",
#"isPost" :#"true"
};
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
AFJSONRequestSerializer *serializer = [AFJSONRequestSerializer serializer];
[serializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[serializer setValue:#"application/json" forHTTPHeaderField:#"Accept"];
manager.requestSerializer = serializer;
[manager.requestSerializer setValue:self.sessionKey forHTTPHeaderField:X_LIVEAGENT_SESSION_KEY];
[manager.requestSerializer setValue:#"null" forHTTPHeaderField:X_LIVEAGENT_AFFINITY];
[manager.requestSerializer setValue:#"1" forHTTPHeaderField:X_LIVEAGENT_SEQUENCE];
[manager.requestSerializer setValue:API_V forHTTPHeaderField:X_LIVEAGENT_API_VERSION];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager POST:ChasitorInit_path parameters:parameters progress:nil
success:^(NSURLSessionDataTask *task, id responseObject) {
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseObject
options:kNilOptions
error:&error];
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"Error: %#", error);
}];
Im using Afnetworking v3 ios8
The request body should be
{
"sessionId": "8f1cfb18-fbd1-4487-90d-e98c0a84e165",
"organizationId": "00D58000000OwMB",
"deploymentId": "57258000000L1mj",
"buttonId": "57358000000L24F",
"userAgent": "",
"language": "en-US",
"screenResolution": "1900x1080",
"visitorName": "Test Visitor",
"prechatDetails": [],
"prechatEntities": [],
"receiveQueueUpdates": true,
"isPost": true
}
What im i doing wrong ? Plz correct me !!
400 Bad request means, you didn't form the request the way server expects.
Check the server logs for whats the issue...
May be it needs data in another form..
and try to check that,you are not passing null value to server..
Try like that:
NSString *Loginurl = [NSString stringWithFormat:#"http://Enter your URL Here"];
NSDictionary *params = #{ #"SessionId" :self.sessionId,
#"OrganizationId" :ORG_ID,
#"deploymentId" :DEPLOYEMENT_ID,
#"buttonId" :BUTTON_ID,
#"userAgent" :USER_AGENT,
#"language" :LANG,
#"screenResolution" :SCREEN_RES,
#"visitorName" :#"Test Visitor",
#"prechatDetails" :#{},
#"prechatEntities" :#{},
#"receiveQueueUpdates":#"true",
#"isPost" :#"true"
};
NSLog(#"Sent parameter to server : %#",params);
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:#"application/json", #"text/json", #"text/javascript",#"text/html", nil];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:#"application/json",#"text/html",nil];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:#"application/json",#"text/plain",nil];
[manager.requestSerializer setValue:self.sessionKey forHTTPHeaderField:X_LIVEAGENT_SESSION_KEY];
[manager.requestSerializer setValue:#"null" forHTTPHeaderField:X_LIVEAGENT_AFFINITY];
[manager.requestSerializer setValue:#"1" forHTTPHeaderField:X_LIVEAGENT_SEQUENCE];
[manager.requestSerializer setValue:API_V forHTTPHeaderField:X_LIVEAGENT_API_VERSION];
AFSecurityPolicy* policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
[policy setValidatesDomainName:NO];
[policy setAllowInvalidCertificates:YES];
[manager POST:Loginurl parameters:params progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(#"Response from server : %#", [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);
_str=[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(#"%#",_str);
[self getdata:responseObject];
} failure:^(NSURLSessionTask *operation, NSError *error)
{
NSLog(#"Error: %#", error);
}];
}
#pragma mark-DataFromServer
-(void)getdata:(NSDictionary*)RegisterData
{
}
I got the same error in my app. I resolve it by removing request and response Serializer. Only instantiate manager and called post method with parameter.
reqManager = [AFHTTPRequestOperationManager manager];
[reqManager POST:URLString parameters:parameters progress:nil
success:^(NSURLSessionDataTask *task, id responseObject) {
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"Error: %#", error);
}];
I am sending GET request to server to getting json response. When i first do it i get some response but then i make changes in the database but still i get the same josn which i was getting.But on browser the json is updated on app it is not updated.I have used below code to make it work but nothing works for me.
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:url]];
[manager.requestSerializer setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
AFJSONRequestSerializer *requestSerializer = [AFJSONRequestSerializer serializer];
[requestSerializer setValue:api_key forHTTPHeaderField:#"Authorization"];
manager.requestSerializer = requestSerializer;
AFJSONResponseSerializer *responseSerializer = [AFJSONResponseSerializer serializer];
responseSerializer.acceptableContentTypes = [NSSet setWithObjects:#"application/json", #"text/json", #"text/javascript", #"text/html", nil];
manager.responseSerializer = responseSerializer;
[manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"json is %#",responseObject);
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
[self activityIndicator:#"hide"];
NSLog(#"Error: %#", operation.responseString);
}];
I have tried reloadignoringcachedata but this does not work.
So - I have identical AFNetworking code, that, when run on the simulator, returns results as expected, and gives me all the proper JSON back.
Soon as I run it on the device, I get a 401. Now, I understand this means 'unauthorized,' but how on earth does it run absolutely swimmingly on the simulator and then give me a 401 on the device?
The code is below and has only been changed to remove the address of our API which must remain private.
phoneNumber = phoneNumberField.text;
[[NSUserDefaults standardUserDefaults] setObject:phoneNumber forKey:#"phone_number"];
NSString *UDIDstring = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
NSLog(#"UDID: %#",UDIDstring);
NSString *jsonRequest = [NSString stringWithFormat:#"{\"userId\":\"%#\",\"userType\":\"%#\",\"deviceId\":\"%#\",\"deviceType\":\"%#\"}",phoneNumberField.text,#"Number",UDIDstring,#"iPhone"];
NSLog(#"json: %#",jsonRequest);
NSDictionary *stuff = [[NSDictionary alloc] initWithObjectsAndKeys:
phoneNumberField.text, #"userId",
#"Number", #"userType",
UDIDstring,#"deviceId",
#"iPhone",#"deviceType",
nil];
NSLog(#"stuff: %#",stuff);
NSError *error;
NSData *postData = [NSJSONSerialization dataWithJSONObject:stuff options:0 error:&error];
NSString *urlString = #"(hidden for privacy reasons)"
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]
cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10];
NSString *userpass = [#"vclient:VastV1" base64EncodedString];
NSLog(#"userpass: %#",userpass);
[request setHTTPMethod:#"POST"];
[request setValue:[NSString stringWithFormat:#"Basic: %#",userpass] forHTTPHeaderField:#"Authorization"];
//[request setValue:#"*/*" forHTTPHeaderField:#"Accept"];
[request setValue: #"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
securityPolicy.allowInvalidCertificates = YES;
op.securityPolicy = securityPolicy;
op.responseSerializer = [AFJSONResponseSerializer serializer];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON responseObject: %# ",responseObject);
[infoLabel setText:#"You have been sent an activation code to the number you used. Please enter it above."];
[signupLabel setText:#"your code:"];
[mainButton setTitle:#"Activate" forState:UIControlStateNormal];
firstSignup=true;
[phoneNumberField setText:#""];
[phoneNumberField setPlaceholder:#"Enter activation code."];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", [error localizedDescription]);
}];
[op start];
One difference would be that you are reporting a different device ID. Maybe the API that you are using keeps track of device IDs that have been authorized. And your Mac has been authorized, but the iOS device hasn't.
You could try logging the device id on the Mac, and then change your code to use that ID as a hardcoded string, instead of using what the iPhone returns.
You can try this, I do it all the time
#import "AFNetworking.h"
NSDictionary *params = #{ #"key1": txtBox1.text, #"key2", txtbox2.text};
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
AFJSONRequestSerializer *serializerRequest = [AFJSONRequestSerializer serializer];
AFJSONResponseSerializer *serializerResponse = [AFJSONResponseSerializer serializer];
[serializerRequest setValue:#"application/json" forHTTPHeaderField:#"Content-Type"]];
serializerResponse.acceptableContentTypes = [NSSet setWithObject:#"application/json"];
manager.requestSerializer = serializerRequest;
manager.responseSerializer = serializerResponse;
[manager.securityPolicy setAllowInvalidCertificates:YES];
[manager POST:#"url"
parameters:params
success:^(AFHTTPRequestOperation *operation, id responseObject) {
// DO WHAT YOU WANT IF SUCCESSED
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// DO WHAT YOU WANT IF FAILED
}];
Are you using an authentication scheme that depends on the time? I've seen drift on the simulator that causes it to 401.
I want to use AFNetworking class to my application to communicating with server.
I am new to this library . Here is my code:
NSDictionary *user=[[NSDictionary alloc]initWithObjectsAndKeys:#"hiteshp",#"userName",#"12345^",#"password", nil];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
AFHTTPRequestSerializer *requestSerializer = [AFHTTPRequestSerializer serializer];
[requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
manager.requestSerializer=requestSerializer; //[AFJSONRequestSerializer serializer];
[manager POST:#"myURL" parameters:user success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %# %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
I want to add header to this request . I tried but it is not working . If I wrote commented line then request is done but I also want to add one more field "Authorization" to requset.
Andhow to print request header?
I know it's too late but here's a code that makes what you want
NSString *finalyToken = [[NSString alloc]initWithFormat:#"Bearer %#",user.token];
AFHTTPRequestOperationManager *manager =
[[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:#"https://server1.appscserver.de/api"]];
[manager.requestSerializer setValue:finalyToken forHTTPHeaderField:#"Authorization"];
Hope it helps someone
Use this in your code:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:#"text/html", #"application/json", nil];
//Authorization
[manager.requestSerializer setAuthorizationHeaderFieldWithUsername:userName password:password];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
in php file add:
header('Content-type: application/json');
in xcode:
manager.responseSerializer = [AFJSONResponseSerializer serializer];
example xcode code:
NSDictionary *parameters = #{#"key1": #"value1",
#"key2": #"value2"};
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager POST:[NSString stringWithFormat:#"http://%#", Url] parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];