In my project i am passing this API: http://dev-demo.info.bh-in-15.webhostbox.net/dv/nationalblack/api/businessbysubcat with params: prod_id=25,var_id=140.
The problem is when i am pass this api in Rest Client it displays correct response but when i am trying to put it in my code it shows different response.
i am using the following code:
-(void)listofNotice
{
NSString *post = [NSString stringWithFormat:#"prod_id=25,var_id=140"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://dev-demo.info.bh-in-15.webhostbox.net/dv/nationalblack/api/businessbysubcat"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
//NSString *str=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
//NSLog(#"str : %#",str);
NSDictionary *dict6 = [self cleanJsonToObject:responseData];
NSLog(#"str : %#",dict6);
}
- (id)cleanJsonToObject:(id)data
{
NSError* error;
if (data == (id)[NSNull null])
{
return [[NSObject alloc] init];
}
id jsonObject;
if ([data isKindOfClass:[NSData class]])
{
jsonObject = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
}
else
{
jsonObject = data;
}
if ([jsonObject isKindOfClass:[NSArray class]])
{
NSMutableArray *array = [jsonObject mutableCopy];
for (int i = (int)array.count-1; i >= 0; i--)
{
id a = array[i];
if (a == (id)[NSNull null])
{
[array removeObjectAtIndex:i];
} else
{
array[i] = [self cleanJsonToObject:a];
}
}
return array;
}
else if ([jsonObject isKindOfClass:[NSDictionary class]])
{
NSMutableDictionary *dictionary = [jsonObject mutableCopy];
for(NSString *key in [dictionary allKeys])
{
id d = dictionary[key];
if (d == (id)[NSNull null])
{
dictionary[key] = #"";
} else
{
dictionary[key] = [self cleanJsonToObject:d];
}
}
return dictionary;
}
else
{
return jsonObject;
}
}
it display the following response:
str : {
business = 0;
"business-list" = "Business list empty.";
response = 401;
}
but the actual response is something like this
please help me.. Thanks In advance
Please change this
NSString *post = [NSString stringWithFormat:#"prod_id=25,var_id=140"];
To:
NSString * post =[NSString stringWithFormat:#"prod_id=25&var_id=140"];
if possible use this:
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
configuration.HTTPAdditionalHeaders = #{#"application/x-www-form-urlencoded" : #"Content-Type"};
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#"http://dev-demo.info.bh-in-15.webhostbox.net/dv/nationalblack/api/businessbysubcat"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSData *requestData = [post dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:requestData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (data != nil){
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
NSInteger code = [httpResponse statusCode];
NSLog(#"Status Code: %ld", (long)code);
if (code == 200) {
NSError *error;
id responseObject =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
}
}
}];
[postDataTask resume];
OR
NSString *postString = [NSString stringWithFormat:#"prod_id=%#&var_id=%#",#"25",#"140"];
NSURL *urlPath = [NSURL URLWithString:#"http://dev-demo.info.bh-in-15.webhostbox.net/dv/nationalblack/api/businessbysubcat"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:urlPath
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
NSData *requestData = [postString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:requestData];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
[APP_DELEGATE removeLoader];
if(data != nil) {
NSDictionary *responseObject =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
NSLog(#" %#", responseObject);
}
else {
}
}];
Hope this helps.
I think you need to change below code
NSString *post = [NSString stringWithFormat:#"prod_id=25,var_id=140"];
to
NSDictionary *prodDict=#{#"prod_id":#"25",
#"var_id":#"140"};
Related
I have a Xcode app which I am updating to the latest iOS. I now notice that on building I have the following error/warning:
/ConfViewController.m:198:46: 'sendSynchronousRequest:returningResponse:error:' is deprecated: first deprecated in iOS 9.0 - Use [NSURLSession dataTaskWithRequest:completionHandler:] (see NSURLSession.h
From what I have read I should start to use "NSURLSession" but how do I use "NSURLSession" in my code, or am I looking at this incorrectly?
My code:
NSString *deviceName = [[UIDevice currentDevice]name];
NSString *post =[[NSString alloc] initWithFormat:#"devicename=%#",deviceName];
NSLog(#"PostData: %#",post);
NSURL *url=[NSURL URLWithString:#"http://www.mydomain/sysscripts/conf/devicelookup17.php"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
//The ERROR point
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
//NSLog(#"Response code: %ld", (long)[response statusCode]);
if ([response statusCode] >=200 && [response statusCode] <300)
{
NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"Response ==> %#", responseData);
SBJsonParser *jsonParser = [SBJsonParser new];
NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:responseData error:nil];
// NSLog(#"%#",jsonData);
// NSInteger success = [(NSNumber *) [jsonData objectForKey:#"success"] integerValue];
NSInteger roomid = [(NSNumber *) [jsonData objectForKey:#"roomid"] integerValue];
// NSLog(#"%ld",(long)success);
//NSLog(#"%ld",(long)roomid);
NSString *RoomID = [NSString stringWithFormat:#"%ld",(long)roomid];
// NSLog(#"%#", RoomID);
NSString *firstString = #"http://www.mydomain/apps/conf/lon/dt/devices/ /template17.php";
// NSLog(#"%#", firstString);
NSString *roomID = RoomID;
// NSLog(#"%#", roomID);
NSString *newString = [firstString stringByReplacingOccurrencesOfString:#" " withString:roomID];
// NSLog(#"%#", newString);
NSURL *url2 = [NSURL URLWithString: newString];
NSLog(#"%#", url2);
NSURLRequest *request2 = [NSURLRequest requestWithURL:url2];
// ConfViewController *navex =[[ConfViewController alloc] initWithNibName:nil bundle:nil];
//[self presentViewController:navex animated:YES completion:NULL];
[webView loadRequest:request2];
}
Many thanks in advance for your time.
Replace
NSData *urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
with
[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * data, NSURLResponse * response, NSError * error) {
}] resume];
Put the entire code after the sendSynchronousRequest line in the completion block (between the braces).
Replace
if ([response statusCode] >=200 && [response statusCode] <300)
with
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
NSInteger statusCode = httpResponse.statusCode;
if (statusCode >= 200 && statusCode < 300)
Replace urlData with data.
Delete
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
I am trying to upload a UIImage to .Net server by converting the image into base 64 and NSData. But I am getting the response null. Here is my code.
NSString *base64Encoded = [imageData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
NSString *post= [NSString stringWithFormat:#"myServerSideUrl?Image=%#",base64Encoded];
NSLog(#"PostData: %#",post);
NSString* webStringURL = [post stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
NSURL* url = [NSURL URLWithString:webStringURL];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error;
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSData *responseData = [[NSData alloc]initWithData:urlData];
if ([response statusCode] >=200 )
{
NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData: responseData options:0 error:nil];
NSLog(#"%#",jsonData);
}
After some time, I just checked in postman showing like url too long HttpResponseCode:414. Also I tried to send the image in NSData format using AFNetwork, getting the same response. And I just googled about this, saying like send the base 64 string in body. When I tried to send image in body, server side can't get the image. They are creating the API like GET method but the actual method is POST. Is there any other solution about this. Any suggestions.
You are setting NSData to your request body without defining any key-value pair.
Try this code using AFNetworking...
- (void) uploadFileRequestWithHttpHeaders:(NSMutableDictionary*) headers
withServiceName:(NSString*) serviceName
withParameters:(NSMutableDictionary*) params
withFileData:(NSArray*) files
{
NSString *serviceUrl = [httpBaseURL stringByAppendingPathComponent:serviceName];
if (headers == nil)
{
NSDictionary *headers = [[NSDictionary alloc] initWithObjectsAndKeys:#"multipart/form-data",#"Content-Type",nil];
[self setHeaders:headers];
}
else
{
[headers setObject:#"multipart/form-data" forKey:#"Content-Type"];
[self setHeaders:headers];
}
[httpSessionManager POST:serviceUrl
parameters:params
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
for (NSData *fileData in files)
{
[formData appendPartWithFileData:fileData name:#"userProfileImg" fileName:#"profile_pic.jpg" mimeType:#"image/jpeg"];
}
}
success:^(NSURLSessionDataTask *task, id responseObject) {
if (success != nil)
}
failure:^(NSURLSessionDataTask *task, NSError *error) {
if (failure != nil)
}];
}
- (void) setHeaders:(NSDictionary*) headers
{
if (headers != nil)
{
NSArray *allHeaders = [headers allKeys];
for (NSString *key in allHeaders)
{
[httpSessionManager.requestSerializer setValue:[headers objectForKey:key] forHTTPHeaderField:key];
}
}
}
- (void) addQueryStringWithParams:(NSDictionary*) params
{
[httpSessionManager.requestSerializer setQueryStringSerializationWithBlock:^NSString *(NSURLRequest *request, NSDictionary *parameters, NSError *__autoreleasing *error) {
__block NSMutableString *query = [NSMutableString stringWithString:#""];
NSError *err;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:0 error:&err];
NSMutableString *jsonString = [[NSMutableString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
query = jsonString;
return query;
}];
}
And call this method like this..
NSArray *objects = [NSArray arrayWithObjects:#"multipart/form-data",#"1.0",#"ios",token, nil];
NSArray *Keys = [NSArray arrayWithObjects:#"content-type",#"version",#"os",#"token", nil];
NSMutableDictionary *headers = [[NSMutableDictionary alloc]initWithObjects:objects forKeys:Keys];
NSMutableDictionary *paraDic = [[NSMutableDictionary alloc] init];
[paraDic setObject:self.userNameField.text forKey:#"name"];
NSData * userProfileImg = UIImageJPEGRepresentation(image, 0.8f);
imageDataArray = [NSArray arrayWithObjects:userProfileImg, nil];
[self uploadFileRequestWithHttpHeaders:headers withServiceName:#"updateProfile" withParameters:params withFileData:files];
You can try this code using NSURLSession-
- (void)postRequestForSubmitDataToServer {
//Put your action URL
NSURL *aUrl = [NSURL URLWithString:#"action_url.php?&attachment=att&submit=submit"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request setHTTPMethod:#"POST"];
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if(error == nil) {
//change JSON type according to ur need.
NSArray *JSON = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingMutableContainers error: &error];
NSLog(#"Data = %#",JSON);
} else {
NSLog(#"%#", error);
}
}];
[postDataTask resume];
}
My form data-
<form action="action_url.php" method="post" enctype="multipart/form-data">
Your Photo: <input type="file" name="attachment" size="25" /><br>
<input type="submit" name="submit" value="Submit" /> </form>
Below is the code. It's using GET method for parsing and request.
- (void)getStudentsWithOptions:(NSString*)getURLString screen:(NSString *)screenString completion:(SkoolBeepCompletion)completion {
if (!completion) return;
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:getURLString]];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (error) {
completion(nil, error);
} else {
NSError *err = nil;
NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&err];
//NSLog(#"dataDict : %#", dataDict);
if (!err) {
if ([screenString isEqualToString:#"My Students"]) {
[CoreDataController deleteAllObjects:#"Students"];
NSDictionary *dicEntry = [dataDict objectForKey:#"return_arr"];
for (NSDictionary *dicInsert in dicEntry) {
[CoreDataController storeStudentsObjects:dicInsert];
[CoreDataController storeChildrenObjects:dicInsert];
}
completion(dataDict, nil);
} else if ([screenString isEqualToString:#"User Settings"]) {
[CoreDataController deleteAllObjects:#"Profile"];
[CoreDataController storeProfileObjects:dataDict];
completion(dataDict, nil);
} else if ([screenString isEqualToString:#"About"]) {
[CoreDataController deleteAllObjects:#"About"];
[CoreDataController storeAboutObjects:dataDict];
completion(dataDict, nil);
} else if ([screenString isEqualToString:#"Works"]) {
[CoreDataController deleteAllObjects:#"Works"];
[CoreDataController storeWorksObjects:dataDict];
completion(dataDict, nil);
} else {
completion(dataDict, nil);
}
} else {
completion(nil, err);
}
}
}];
}
Above is line of code that I want in POST.
URLRequest must be using POST type.
I have added the code in my question.
Use NSMutableURLRequest for POST
NSString *Post=[NSString stringWithFormat:#"email=%#&password=%#",#"iamiosguy#gmail.com",#"lovetocode"];
NSData *PostData = [Post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO];
NSString *PostLengh=[NSString stringWithFormat:#"%d",[Post length]];
NSURL *Url=[NSURL URLWithString: #"Your URL"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:Url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setHTTPMethod:#"POST"];
[request setValue:PostLengh forHTTPHeaderField:#"Content-Lenght"];
[request setHTTPBody:PostData];
NSData *ReturnData =[NSURLConnection sendSynchronousRequest:request returningResponse:Nil error:Nil];
NSString *Response = [[NSString alloc] initWithData:ReturnData encoding:NSUTF8StringEncoding];
NSLog(#"Response%#",Response);
I have a NSString which contains the URL. I want to make a GET request using the URL and also check if the response is 200.
With the current code i get response as 0.
Here is my code:
NSString *Url = #"http://www.xyx.com";
NSData *data = [Url dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *len = [NSString stringWithFormat:#"%lu", (unsigned long)[data length]];
NSMutableURLRequest *req = [[NSMutableURLRequest alloc]init];
[req setURL:[NSURL URLWithString:Url]];
[req setHTTPMethod:#"GET"];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:req completionHandler:^(NSData data, NSURLResponse response, NSError *error) {
NSString *req = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"Reply = %#", req);
}]resume];
use this code it works for you:
-(void)yourMethodNAme
{
NSString *post = #"";
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"Your URL"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
//NSString *str=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
//NSLog(#"str : %#",str);
NSDictionary *dict6 = [self cleanJsonToObject:responseData];
//NSLog(#"str : %#",dict6);
}
- (id)cleanJsonToObject:(id)data
{
NSError* error;
if (data == (id)[NSNull null])
{
return [[NSObject alloc] init];
}
id jsonObject;
if ([data isKindOfClass:[NSData class]])
{
jsonObject = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
}
else
{
jsonObject = data;
}
if ([jsonObject isKindOfClass:[NSArray class]])
{
NSMutableArray *array = [jsonObject mutableCopy];
for (int i = (int)array.count-1; i >= 0; i--)
{
id a = array[i];
if (a == (id)[NSNull null])
{
[array removeObjectAtIndex:i];
} else
{
array[i] = [self cleanJsonToObject:a];
}
}
return array;
}
else if ([jsonObject isKindOfClass:[NSDictionary class]])
{
NSMutableDictionary *dictionary = [jsonObject mutableCopy];
for(NSString *key in [dictionary allKeys])
{
id d = dictionary[key];
if (d == (id)[NSNull null])
{
dictionary[key] = #"";
} else
{
dictionary[key] = [self cleanJsonToObject:d];
}
}
return dictionary;
}
else
{
return jsonObject;
}
}
and finally call it in ViewDidLoad as [self yourMethodNAme];
-(void) httpGetWithCustomDelegateWithString: (NSString*)urlString
{
[self startActivity];
[[UIApplication sharedApplication] beginIgnoringInteractionEvents];
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];
NSURL *url = [NSURL URLWithString:urlString];
NSURLSessionDataTask *dataTask =[defaultSession dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
NSLog(#"Response:%# %#\n", response, error);
if(error == nil)
{
//NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
//NSLog(#"Data = %#",text);
id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
deserializedDictionary = nil;
if (jsonObject != nil && error == nil)
{
if ([jsonObject isKindOfClass:[NSDictionary class]])
{
//Convert the NSData to NSDictionary in this final step
deserializedDictionary = (NSDictionary *)jsonObject;
NSLog(#"dictionary : %#",deserializedDictionary);
}
if ([jsonObject isKindOfClass:[NSArray class]])
{
deserializedArr = (NSArray*)jsonObject;
NSLog(#"array : %#",deserializedArr);
}
}
[self setAlert];
}
else
{
[activityView removeFromSuperview];
[[UIApplication sharedApplication] endIgnoringInteractionEvents];
[self showAlert:#"Error" :#"Network error occured." :#"Ok"];
}
}];
[dataTask resume];
}
just use the above code and call it by
[self httpGetWithCustomDelegateWithString:#"webStringHere"];
On Completion, it will call the method -(void)setAlert; so declare it in your class where you use this.
This may be due to App Transport Security blocking HTTP.
App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app's Info.plist file.
Try making a request to a secure site (e.g. https://www.google.com) as a test.
I have a simple app which makes a POST request. And then data is returned. The problem is that the returned data is not JSON..... So how can I view it? Here is my code:
NSString *requestString = [NSString stringWithFormat:#"https://serveraddress.com"];
NSString *string = [NSString stringWithFormat:#"id=%#&olt_info=%#", #"test", #"renz"];
NSData *postData = [string dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:requestString]];
NSLog(#"\n request str : %#",request);
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSHTTPURLResponse *response = nil;
NSError *error = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"The responce:\n\n%#", responseData);
if (error == nil && response.statusCode == 200) {
NSLog(#"%li", (long)response.statusCode);
NSError *err;
id JSon = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&err];
if (err) {
NSLog(#"%#",err);
}
else {
NSLog(#"Json %#",JSon);
}
}
else {
//Error handling
NSLog(#"%#", response);
}
This is the format of the returned data that I am trying to read:
new_token=509723045780uIRBWRBH24b
So I know the downloaded data gets stored in the NSData called "responseData". But if I print it using NSLog I just get this:
<61636365 73735f74 6f6b656e 3d313538 32353838 33343337 39343431 7c365f4d 6543436e 6b51716f 722d6e70 61746662 484d6458 526b3477>
So how do I read this???
Thank you for your time, Dan.
To get NSString from NSData use
NSString *decodedString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
maybe this string will have a valid JSON format.
NSString *requestString = [NSString stringWithFormat:#"https://serveraddress.com"];
NSString *string = [NSString stringWithFormat:#"id=%#&olt_info=%#", #"test", #"renz"];
NSData *postData = [string dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:requestString]];
NSLog(#"\n request str : %#",request);
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSHTTPURLResponse *response = nil;
NSError *error = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
*id json = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:nil];*
NSLog(#"%#", json);
if (error == nil && response.statusCode == 200) {
NSLog(#"%li", (long)response.statusCode);
NSError *err;
id JSon = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&err];
if (err) {
NSLog(#"%#",err);
}
else {
NSLog(#"Json %#",JSon);
}
}
else {
//Error handling
NSLog(#"%#", response);
}