DocuSign error downloading document - iphone

I'm trying to implement this example link of a DocuSign service that download an envelope document, but when the execution arrive to this line in step 3:
NSMutableString *jsonResponse = [[NSMutableString alloc] initWithData:oResponseData encoding:NSUTF8StringEncoding];
jsonResponse is nil and when I open the document, it has a lot of strange characters and I can't read it.
My code for downloadind is the following:
NSString *url = #"https://demo.docusign.net/restapi/v2/accounts/373577/envelopes/08016140-e4dc-4697-8146-f8ce801abf92/documents/1";
NSMutableURLRequest *documentsRequest = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
[documentsRequest setHTTPMethod:#"GET"];
[documentsRequest setURL:[NSURL URLWithString:url]];
[documentsRequest setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[documentsRequest setValue:[self jsonStringFromObject:authenticationHeader] forHTTPHeaderField:#"X-DocuSign-Authentication"];
NSError *error1 = [[NSError alloc] init];
NSHTTPURLResponse *responseCode = nil;
NSData *oResponseData = [NSURLConnection sendSynchronousRequest:documentsRequest returningResponse:&responseCode error:&error1];
NSMutableString *jsonResponse = [[NSMutableString alloc] initWithData:oResponseData encoding:NSUTF8StringEncoding];
if([responseCode statusCode] != 200){
NSLog(#"Error sending %# request to %#\nHTTP status code = %i", [documentsRequest HTTPMethod], url, [responseCode statusCode]);
NSLog( #"Response = %#", jsonResponse );
return;
}
// download the document to the same directory as this app
NSString *appDirectory = [[[NSBundle mainBundle] bundlePath] stringByDeletingLastPathComponent];
NSMutableString *filePath = [NSMutableString stringWithFormat:#"%#/%#", appDirectory, #"eee"];
[oResponseData writeToFile:filePath atomically:YES];
NSLog(#"Envelope document - %# - has been downloaded to %#\n", #"eee", filePath);

If no data is coming back from
NSMutableString *jsonResponse = [[NSMutableString alloc] initWithData:oResponseData encoding:NSUTF8StringEncoding];
then that means oResponseData is most likely nil which means the URL is not being constructed correctly for each envelope document. Are you doing step 2 in the sample that you linked to, where it first retrieves the envelopeDocuments information about the envelope, then it dynamically builds each unique document uri in preparation of downloading each one.
Instead of hardcoding your URL you should dynamically retrieve the envelopeDocuments data, then build each document uri dynamically then your response data will not be nil. Here's the full working sample:
- (void)getDocumentInfoAndDownloadDocuments
{
// Enter your info:
NSString *email = #"<#email#>";
NSString *password = #"<#password#>";
NSString *integratorKey = #"<#integratorKey#>";
// need to copy a valid envelopeId from your account
NSString *envelopeId = #"<#envelopeId#>";
///////////////////////////////////////////////////////////////////////////////////////
// STEP 1 - Login (retrieves accountId and baseUrl)
///////////////////////////////////////////////////////////////////////////////////////
NSString *loginURL = #"https://demo.docusign.net/restapi/v2/login_information";
NSMutableURLRequest *loginRequest = [[NSMutableURLRequest alloc] init];
[loginRequest setHTTPMethod:#"GET"];
[loginRequest setURL:[NSURL URLWithString:loginURL]];
// set JSON formatted X-DocuSign-Authentication header (XML also accepted)
NSDictionary *authenticationHeader = #{#"Username": email, #"Password" : password, #"IntegratorKey" : integratorKey};
// jsonStringFromObject() function defined further below...
[loginRequest setValue:[self jsonStringFromObject:authenticationHeader] forHTTPHeaderField:#"X-DocuSign-Authentication"];
// also set the Content-Type header (other accepted type is application/xml)
[loginRequest setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[NSURLConnection sendAsynchronousRequest:loginRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *loginResponse, NSData *loginData, NSError *loginError) {
if (loginError) { // succesful GET returns status 200
NSLog(#"Error sending request %#. Got Response %# Error is: %#", loginRequest, loginResponse, loginError);
return;
}
// we use NSJSONSerialization to parse the JSON formatted response
NSError *jsonError = nil;
NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:loginData options:kNilOptions error:&jsonError];
NSArray *loginArray = responseDictionary[#"loginAccounts"];
// parse the accountId and baseUrl from the response (other data included)
NSString *accountId = loginArray[0][#"accountId"];
NSString *baseUrl = loginArray[0][#"baseUrl"];
//--- display results
NSLog(#"\naccountId = %#\nbaseUrl = %#\n", accountId, baseUrl);
///////////////////////////////////////////////////////////////////////////////////////
// STEP 2 - Get Document Info for specified envelope
///////////////////////////////////////////////////////////////////////////////////////
// append /envelopes/{envelopeId}/documents URI to baseUrl and use as endpoint for next request
NSString *documentsURL = [NSMutableString stringWithFormat:#"%#/envelopes/%#/documents", baseUrl, envelopeId];
NSMutableURLRequest *documentsRequest = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:documentsURL]];
[documentsRequest setHTTPMethod:#"GET"];
[documentsRequest setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[documentsRequest setValue:[self jsonStringFromObject:authenticationHeader] forHTTPHeaderField:#"X-DocuSign-Authentication"];
[NSURLConnection sendAsynchronousRequest:documentsRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *documentsResponse, NSData *documentsData, NSError *documentsError) {
NSError *documentsJSONError = nil;
NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:documentsData options:kNilOptions error:&documentsJSONError];
if (documentsError){
NSLog(#"Error sending request: %#. Got response: %#", documentsRequest, documentsResponse);
NSLog( #"Response = %#", documentsResponse );
return;
}
NSLog( #"Documents info for envelope is:\n%#", jsonResponse);
NSError *jsonError = nil;
NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:documentsData options:kNilOptions error:&jsonError];
// grab documents info for the next step...
NSArray *documentsArray = responseDictionary[#"envelopeDocuments"];
///////////////////////////////////////////////////////////////////////////////////////
// STEP 3 - Download each envelope document
///////////////////////////////////////////////////////////////////////////////////////
NSMutableString *docUri;
NSMutableString *docName;
NSMutableString *docURL;
// loop through each document uri and download each doc (including the envelope's certificate)
for (int i = 0; i < [documentsArray count]; i++)
{
docUri = [documentsArray[i] objectForKey:#"uri"];
docName = [documentsArray[i] objectForKey:#"name"];
docURL = [NSMutableString stringWithFormat: #"%#/%#", baseUrl, docUri];
[documentsRequest setHTTPMethod:#"GET"];
[documentsRequest setURL:[NSURL URLWithString:docURL]];
[documentsRequest setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[documentsRequest setValue:[self jsonStringFromObject:authenticationHeader] forHTTPHeaderField:#"X-DocuSign-Authentication"];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *responseCode = nil;
NSData *oResponseData = [NSURLConnection sendSynchronousRequest:documentsRequest returningResponse:&responseCode error:&error];
NSMutableString *jsonResponse = [[NSMutableString alloc] initWithData:oResponseData encoding:NSUTF8StringEncoding];
if([responseCode statusCode] != 200){
NSLog(#"Error sending %# request to %#\nHTTP status code = %i", [documentsRequest HTTPMethod], docURL, [responseCode statusCode]);
NSLog( #"Response = %#", jsonResponse );
return;
}
// download the document to the same directory as this app
NSString *appDirectory = [[[NSBundle mainBundle] bundlePath] stringByDeletingLastPathComponent];
NSMutableString *filePath = [NSMutableString stringWithFormat:#"%#/%#", appDirectory, docName];
[oResponseData writeToFile:filePath atomically:YES];
NSLog(#"Envelope document - %# - has been downloaded to %#\n", docName, filePath);
} // end for
}];
}];
}
- (NSString *)jsonStringFromObject:(id)object {
NSString *string = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:object options:0 error:nil] encoding:NSUTF8StringEncoding];
return string;
}

Related

csrf token validation failed for drupal services from iphone request

1.Is it necessary https://www.mysite.com/my_services/user/token
get that token and i set for login call but its get error 'csrf token issue'
before https://www.mysite.com/my_services/user/login
with post paramater username and password
i am question
whether i have to call user/token every time ..for getting token and set the x-csrf-token value in header for post requests.
(void)viewDidLoad
{
[super viewDidLoad];
NSString *notificationName = #"MTPostNotificationTut";
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:#selector(useNotificationWithString:)
name:notificationName
object:nil];
}
(void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
-(void)viewWillAppear:(BOOL)animated {
NSString *urlString = #"https://www.mysite.com/my_services/user/token.json";
NSString *urlS = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlS]cachePolicy:NSURLCacheStorageAllowed timeoutInterval:10.0];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *string = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"stringFromData = %#",string);
id jsonResponseData = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:nil];
NSLog(#"jsonResponseData = %#",jsonResponseData);
NSDictionary *jsonResponseDict;
if ([jsonResponseData isKindOfClass:[NSDictionary class]]) {
jsonResponseDict = jsonResponseData;
} else {
// Error-handling code
}
jsonResponseData = [jsonResponseDict objectForKey:#"d"];
if (jsonResponseData == nil) {
id jsonExceptioTypeData = [jsonResponseDict objectForKey:#"ExceptionType"];
if (jsonExceptioTypeData != nil) {
NSLog(#"%s ERROR : Server returned an exception", __func__);
NSLog(#"%s ERROR : Server error details = %#", __func__, jsonResponseDict);
}
}
token = [jsonResponseDict objectForKey:#"token"];
NSLog(#"token = %#",token);
if (token !=NULL) {
NSString *notificationName = #"MTPostNotificationTut";
NSString *key = #"token";
NSDictionary *dictionary = [NSDictionary dictionaryWithObject:token forKey:key];
[[NSNotificationCenter defaultCenter] postNotificationName:notificationName object:nil userInfo:dictionary];
}
}
-(void)checkWithServer:(NSString *)urlname jsonString:(NSString *)jsonString {
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlname]cachePolicy:NSURLCacheStorageAllowed timeoutInterval:10.0];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *string = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"stringFromData = %#",string);
id jsonResponseData = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:nil];
NSDictionary *jsonResponseDict;
if ([jsonResponseData isKindOfClass:[NSDictionary class]]) {
jsonResponseDict = jsonResponseData;
} else {
}
jsonResponseData = [jsonResponseDict objectForKey:#"d"];
if (jsonResponseData == nil) {
id jsonExceptioTypeData = [jsonResponseDict objectForKey:#"ExceptionType"];
if (jsonExceptioTypeData != nil) {
NSLog(#"%s ERROR : Server returned an exception", __func__);
NSLog(#"%s ERROR : Server error details = %#", __func__, jsonResponseDict);
}
}
NSLog(#"jsonResponseData = %#",jsonResponseDict);
token = [jsonResponseDict objectForKey:#"token"];
NSLog(#"token = %#",token);
}
-(void)useNotificationWithString:(NSNotification*)notification {
NSString *urlString = #"https://www.mysite.com/my_services/user/login.json";
NSString *urlS = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSDictionary *inputData = [[NSDictionary alloc] initWithObjectsAndKeys:
#"ranjeet.gholave", #"username",
#"ran123", #"password",
nil];
NSError *error = nil;
NSData *jsonInputData = [NSJSONSerialization dataWithJSONObject:inputData options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonInputString = [[NSString alloc] initWithData:jsonInputData encoding:NSUTF8StringEncoding];
[self getTokenFromServer:urlS jsonString:jsonInputString];
}
-(void)getTokenFromServer:(NSString *)urlname jsonString:(NSString *)jsonString {
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlname]cachePolicy:NSURLCacheStorageAllowed timeoutInterval:30.0];
[request setHTTPMethod:#"POST"];
// [request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request addValue:token forHTTPHeaderField:#"X-CSRFToken"];
[request setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSLog(#"responseDataIn Second Method = %#",responseData);
id jsonResponseData = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:nil];
NSLog(#"jsonResponseData = %#",jsonResponseData);
NSDictionary *jsonResponseDict;
if ([jsonResponseData isKindOfClass:[NSDictionary class]]) {
jsonResponseDict = jsonResponseData;
} else {
// Error-handling code
}
jsonResponseData = [jsonResponseDict objectForKey:#"d"];
if (jsonResponseData == nil) {
id jsonExceptioTypeData = [jsonResponseDict objectForKey:#"ExceptionType"];
if (jsonExceptioTypeData != nil) {
NSLog(#"%s ERROR : Server returned an exception", __func__);
NSLog(#"%s ERROR : Server error details = %#", __func__, jsonResponseDict);
}
}
}
if i cookie allowed then csrf token validation issue comes
and when i cookie not allowed then csrf token issue not comes ....how to resolved issue..thanks
Regards,
Ranjeet Gholave
I know this is a bit of an old thread. But you should check out https://github.com/kylebrowning/drupal-ios-sdk as well as AFNetworking. You're really working way harder than you have to.
But to answer your question, once you log in, the CSRF token will be returned in the user object and will be valid for then entire user session. So you can cache it and use it until the user logs out or their session expires.
With Drupal IOS SDK it is as simple as:
[DIOSUser userMakeSureUserIsLoggedInWithUsername:username
andPassword:password
success:^(AFHTTPRequestOperation *op, id response) {
DLog(#"user: %#", response);
[DIOSSession sharedSession].user = response;
//NOTE: fix for services 3.4+ CSRF Token Validation
[[DIOSSession sharedSession] setDefaultHeader:#"X-CSRF-Token" value:response[#"token"]];
[self saveLoginInfoForUserWithUsername:username andPassword:password];
[self processUserInfoWithUser:response];
success(response);
}
failure:^(AFHTTPRequestOperation *op, NSError *err) {
failure(err);
}
];

how to call webservice in xcode by GET Method?

I have this link :
function new_message($chat_id,$user_id,$message,$recipient_ids)
http://www.demii.com/demo/dooponz/admin/index.php/chat/new_message/4/1/you/2%2C7
return chat_log_id
Can anyone please explain me how to call webserive by this get method or give me the
solution .
what i did with my code is below :
-(void)newMessage{
if ([self connectedToWiFi]){
NSString *urlString = [NSString stringWithFormat:#"www.demii.com/demo/dooponz/admin/index.php/chat/new_message/4/1/you/1,1,2"];
NSLog(#"urlString is %#", urlString);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSURL *requestURL = [NSURL URLWithString:urlString];
[request setURL:requestURL];
[request setHTTPMethod:#"POST"];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSLog(#"ERROR = %#",error.localizedDescription);
if(error.localizedDescription == NULL)
{
NSString *returnString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"response >>>>>>>>> succ %#",returnString);
[delegate ConnectionDidFinishLoading:returnString : #"newMessage"];
}
else
{
NSString *returnString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"response >>>>>>>>> fail %#",returnString);
[delegate ConnectiondidFailWithError:returnString : #"newMessage"];
}
}];
}
}
how can i handle this ?
Thanks in advance .
I am not sure from your post whether or not you want to "post" or "get." However, gauging from the fact that you set your method to post, and that you are creating something new on your server, I am assuming you want to post.
If you want to post you can use my wrapper method for a post request.
+ (NSData *) myPostRequest: (NSString *) requestString withURL: (NSURL *) url{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setTimeoutInterval:15.0];
NSData *requestBody = [requestString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
[request setHTTPBody:requestBody];
NSURLResponse *response = NULL;
NSError *requestError = NULL;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];
return responseData;
}
Where request string is formatted like this:
NSString * requestString = [[NSString alloc] initWithFormat:#"username=%#&password=%#", userInfo[#"username"], userInfo[#"password"]];
This will also shoot back the response data which you can turn into a string like this.
responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
If you are trying to grab data from the server in json format...
+ (NSArray *) myGetRequest: (NSURL *) url{
NSArray *json = [[NSArray alloc] init];
NSData* data = [NSData dataWithContentsOfURL:
url];
NSError *error;
if (data)
json = [[NSArray alloc] initWithArray:[NSJSONSerialization
JSONObjectWithData:data
options:kNilOptions
error:&error]];
//NSLog(#"get results: \n %#", json);
return json;
}
Pls change ur code like this
-(void)newMessage{
NSString *urlString = [NSString stringWithFormat:#"http://www.demii.com/demo/dooponz/admin/index.php/chat/new_message/4/1/you/27" ];
NSLog(#"urlString is %#", urlString);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSURL *requestURL = [NSURL URLWithString:urlString];
[request setURL:requestURL];
[request setHTTPMethod:#"POST"];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSLog(#"ERROR = %#",error.localizedDescription);
if(error.localizedDescription == NULL)
{
NSString *returnString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"response >>>>>>>>> succ %#",returnString);
[self parseStringtoJSON:data];
//[delegate ConnectionDidFinishLoading:returnString : #"newMessage"];
}
else
{
NSString *returnString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"response >>>>>>>>> fail %#",returnString);
// [delegate ConnectiondidFailWithError:returnString : #"newMessage"];
}
}];
}
-(void)parseStringtoJSON:(NSData *)data{
NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSLog(#"chat id %#",[dict objectForKey:#"chat_log_id"]);
}
u will get the JSON response string as result if u hit that url. If u r familiar with json parsing, u can get the value based on key.
see this link: How do I deserialize a JSON string into an NSDictionary? (For iOS 5+)

URL Decoding of json in ios

I am having 1 webservice in php which is having browser url mentioned bel :
http:Domain/webservice/ACTEC_WebService.php?lastupdate=2012-09-01 01:00:00
Now when I try to fetch url in my iphone app, it is taking this url:
http://Domain/webservice/ACTEC_WebService.php?lastupdate=2012-09-01%2001:00:00
This is creating problem.
i have used this code for fetching data from my url.
SBJSON *json = [SBJSON new];
json.humanReadable = YES;
responseData = [[NSMutableData data] retain];
NSString *service = #"";
NSString *str;
str = #"LastUpdated";
NSString *requestString = [NSString stringWithFormat:#"{\"LastUpdated\":\"%#\"}",str];
// [[NSUserDefaults standardUserDefaults] setValue:nil forKey:#"WRONGANSWER"];
NSLog(#"request string:%#",requestString);
NSData *requestData = [NSData dataWithBytes: [requestString UTF8String] length: [requestString length]];
NSString *fileLoc = [[NSBundle mainBundle] pathForResource:#"URLName" ofType:#"plist"];
NSDictionary *fileContents = [[NSDictionary alloc] initWithContentsOfFile:fileLoc];
NSString *urlLoc = [fileContents objectForKey:#"URL"];
//urlLoc = [urlLoc stringByAppendingString:service];
NSLog(#"URL : %#",urlLoc);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:
[NSURL URLWithString:urlLoc]];
NSString *postLength = [NSString stringWithFormat:#"%d", [requestData length]];
[request setHTTPMethod: #"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:requestData];
NSError *respError = nil;
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: &respError ];
NSString *responseString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];
NSLog(#"Resp : %#",responseString);
if (respError)
{
// NSString *msg = [NSString stringWithFormat:#"Connection failed! Error - %# %#",
// [respError localizedDescription],
// [[respError userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"ACTEC"
message:#"check your network connection" delegate:self cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
[alertView release];
}
else
{
......
}
here,i am getting null response as url is getting decoded...How can I make this solved...
Help me out.
Thanks in advance.
NSString *urlLoc = [[fileContents objectForKey:#"URL"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableData *postData = [NSMutableData data];
NSMutableURLRequest *urlRequest;
[postData appendData: [[NSString stringWithFormat: #"add your data which you want to send"] dataUsingEncoding: NSUTF8StringEncoding]];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
urlRequest = [[NSMutableURLRequest alloc] init];
[urlRequest setURL:[NSURL URLWithString:urlLoc]];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setValue:postLength forHTTPHeaderField:#"Content-Length"];
[urlRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[urlRequest setHTTPBody:postData];
NSString *temp = [[NSString alloc] initWithData:postData encoding:NSUTF8StringEncoding];
NSLog(#"\n\nurl =%# \n posted data =>%#",urlLoc, temp);
check nslog. that which data u send to service.
NSData *response = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSLog(#"json_string >> %#",json_string);
Maybe this will help you.
hey dear just for an another example i just post my this code..
first Create new SBJSON parser object
SBJSON *parser = [[SBJSON alloc] init];
NSURLRequest *request = [NSURLRequest requestWithURL:
    [NSURL URLWithString:#"http:Domain/webservice/ACTEC_WebService.php?lastupdate=2012-09-01%2001:00:00"]];
Perform request and get JSON back as a NSData object
NSData *response = [NSURLConnection sendSynchronousRequest:request
    returningResponse:nil error:nil];
Get JSON as a NSString from NSData response
NSString *json_string = [[NSString alloc]
    initWithData:response encoding:NSUTF8StringEncoding];
Parse the JSON response into an object Here we're using NSArray since we're parsing an array of JSON status objects
NSArray *statuses = [parser objectWithString:json_string error:nil]
And in statuses array you have all the data you need.
i hope this help you...
:)

HTTP Post using JSON for UIImage

I am attempting to leverage http POST to send a JSON object (UIImage is included in POST). Below is the code I am currently using, but for some reason the server is not receiving the POST. Can anyone provide insight as to why this may not be working?
NSString *userString = [[NSString alloc]init];
userString = [[NSUserDefaults standardUserDefaults]valueForKey:#"userId"];
//convert image to nsdata object
NSData *imageData = UIImageJPEGRepresentation(imageView.image, .9);
NSLog(#"User id is:%#", userString);
NSLog(#"The tag string:%#", myTagString);
NSLog(#"the question string is:%#", myQuestionString);
NSLog(#"the image data is:%#", imageData);
NSArray *keys = [NSArray arrayWithObjects:#"category", #"question", #"latitude", #"longitude", #"user_id", #"image",nil];
NSArray *objects = [NSArray arrayWithObjects:myTagString, myQuestionString, #"0.0", #"0.0", userString, imageData, nil];
NSDictionary *theRequestDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSURL *theURL = [NSURL URLWithString:#"http://theserver.com/query"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:theURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10.0f];
[theRequest setHTTPMethod:#"POST"];
[theRequest setValue:#"application/json-rpc" forHTTPHeaderField:#"Content-Type"];
NSString *theBodyString = [[NSString alloc]init];
theBodyString = [[CJSONSerializer serializer] serializeDictionary:theRequestDictionary];
NSLog(#"body string: %#", theBodyString);
NSData *theBodyData = [theBodyString dataUsingEncoding:NSUTF8StringEncoding];
NSLog(#"body data: %#", theBodyData);
[theRequest setHTTPBody:theBodyData];
NSURLResponse *theResponse = NULL;
NSError *theError = NULL;
NSData *theResponseData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&theResponse error:&theError];
NSString *theResponseString = [[[NSString alloc] initWithData:theResponseData encoding:NSUTF8StringEncoding] autorelease];
NSLog(#"the response string:%#", theResponseString);
NSDictionary *theResponseDictionary = [[CJSONDeserializer deserializer] deserialize:theResponseData error:nil];
NSLog(#"%#", theResponseDictionary);
This is my first post in a forum so I apologize if some of the formatting is wrong. Feel free to critique it so I can submit better posts in the future.
Take a look at the code in this project of mine in Github http://akos.ma/7qp where the Wrapper class sets a couple of headers in the request, so that the server can process the binary data being uploaded. Look at the uploadData:toUrl: method in line 118, which sets the required content type headers.

Marking items as read / unread in iphone google reader app

I am developing an app using data from google reader's API and using GData for login.
I want to be able to mark a post inside a table cell as read / unread, but am finding the fact that this is all mainly undocumented hard to work out a solution, any ideas / links?
Here is the code for the mark read button:
//Get the token
NSString *tokenString = [NSString stringWithFormat:#"https://www.google.com/reader/api/0/token"];
NSURL *tokenURL = [NSURL URLWithString:tokenString];
NSMutableURLRequest *tokenRequest = [NSMutableURLRequest requestWithURL:tokenURL];
NSString *tokenStringResult;
NSArray *listItems;
NSError *tokenError = nil;
NSURLResponse *tokenResponse = nil;
NSData *tokenData = [NSURLConnection sendSynchronousRequest:tokenRequest
returningResponse:&tokenResponse
error:&tokenError];
if (tokenData)
{
tokenStringResult = [[NSString alloc] initWithData:tokenData encoding:NSUTF8StringEncoding];
listItems = [tokenStringResult componentsSeparatedByString:#"/"];
}
else
{
NSLog(#"tokenError = %#", tokenError);
}
// Mark it as read
NSString *readerURLString = [NSString stringWithFormat:#"http://www.google.com/reader/api/0/edit-tag?a=user/-/state/com.google/read&async=true&s=feed/%#&i=%#&T=%#", siteLink, postID, [listItems lastObject]];
NSURL *readerURL = [NSURL URLWithString:readerURLString];
NSMutableURLRequest *readerRequest = [NSMutableURLRequest requestWithURL:readerURL];
[mAuth authorizeRequest:readerRequest];
NSError *error = nil;
NSURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:readerRequest
returningResponse:&response
error:&error];
if (data)
{
NSHTTPURLResponse * httpResponse = (NSHTTPURLResponse *) response;
assert( [httpResponse isKindOfClass:[NSHTTPURLResponse class]] );
NSLog(#"response.allHeaderFields = %#", [httpResponse allHeaderFields]);
NSLog(#"response.statusCode = %i", [httpResponse statusCode]);
}
the log from this is:
response.statusCode = {
"Cache-Control" = "private, max-age=0";
"Content-Length" = 1334;
"Content-Type" = "text/html; charset=UTF-8";
Date = "Fri, 21 Jan 2011 03:49:07 GMT";
Expires = "Fri, 21 Jan 2011 03:49:07 GMT";
Server = GSE;
"X-Content-Type-Options" = nosniff;
"X-Frame-Options" = SAMEORIGIN;
"X-Reader-Google-Version" = "527-000";
"X-Reader-User" = 01940378872835844713;
"X-Xss-Protection" = "1; mode=block";
}
response.statusCode = 400
So through alot of trial and error I've got it working.
EDIT - Added Auth code
NSString *GOOGLE_CLIENT_AUTH_URL = #"https://www.google.com/accounts/ClientLogin?client=SomeName";
NSString *gSourceString = #"SomeName";
NSMutableURLRequest *httpReq = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:GOOGLE_CLIENT_AUTH_URL]];
[httpReq setTimeoutInterval:30.0];
[httpReq setCachePolicy:NSURLRequestReloadIgnoringCacheData];
[httpReq setHTTPMethod:#"POST"];
[httpReq addValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSString *requestBody = [[NSString alloc] initWithFormat:#"Email=%#&Passwd=%#&service=reader&accountType=HOSTED_OR_GOOGLE&source=%#", userString, passwordString, [NSString stringWithFormat:#"%#%d", gSourceString]];
[httpReq setHTTPBody:[requestBody dataUsingEncoding:NSASCIIStringEncoding]];
[requestBody release];
NSHTTPURLResponse *response = nil;
NSData *data = nil;
NSString *responseStr = nil;
NSArray *responseLines = nil;
int responseStatus = 0;
data = [NSURLConnection sendSynchronousRequest:httpReq returningResponse:&response error:&error];
[httpReq release];
if ([data length] > 0)
{
responseStr = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
responseStatus = [response statusCode];
if (responseStatus == 200 )
{
authOK = TRUE;
NSLog(#"Successfully authenticated with Google.");
NSArray *authLines = nil;
authLines = [responseStr componentsSeparatedByString:#"\n"];
int j;
for (j =0; j < [authLines count]; j++ )
{
if ([[authLines objectAtIndex:j] rangeOfString:#"Auth="].length != 0) {
NSMutableString *teststring = [NSMutableString stringWithString:[authLines objectAtIndex:j]];
[teststring replaceCharactersInRange:NSMakeRange(0,4) withString:#"auth"];
authString = teststring;
}
}
}
}
NSString *auth = [[NSString alloc] initWithString: [NSString stringWithFormat:#"GoogleLogin %#", authString]];
NSDictionary *createHeader = [[NSDictionary dictionaryWithObjectsAndKeys:#"www.google.com", #"Host", #"EditApp", #"User-Agent", #"gzip, deflate", #"Accept-Encoding", auth, #"Authorization", nil]retain];
[auth release];
NSURL *url =[NSURL URLWithString:#"http://www.google.com/reader/api/0/token?client=EditApp"];
NSData *recieveData;
NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc]initWithURL:url];
[urlRequest setHTTPMethod:#"GET"];
[urlRequest setAllHTTPHeaderFields:createHeader];
NSURLResponse *response;
NSError *error;
recieveData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];
// Get token
NSString *pretokenString = [[NSString alloc] initWithData:recieveData encoding:NSASCIIStringEncoding];
tokenString = [pretokenString substringWithRange:NSMakeRange(2, [pretokenString length]-2)];
[pretokenString release];
[urlRequest release];
NSMutableURLRequest *thttpReq = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://www.google.com/reader/api/0/edit-tag?"]];
[thttpReq setTimeoutInterval:30.0];
[thttpReq setHTTPMethod:#"POST"];
NSString *authHeader = [NSString stringWithFormat:#"GoogleLogin %#", authString];
[thttpReq addValue:authHeader forHTTPHeaderField:#"Authorization"];
[thttpReq addValue:#"Content-Type" forHTTPHeaderField:#"application/x-www-form-urlencoded"];
// siteLink is the url of the feed
// googlePostID is the id from the XML output: tag:google.com,2005:reader/item/e3345c69e174bdec
NSString *trequestBody = [[NSString alloc] initWithFormat:#"a=user/-/state/com.google/read&ac=edit-tags&s=feed/%#&i=%#&T=%#", siteLink, googlePostID, tokenString];
[thttpReq setHTTPBody:[trequestBody dataUsingEncoding:NSASCIIStringEncoding]];
NSURLConnection *con = [[NSURLConnection alloc]
initWithRequest:thttpReq
delegate:self
startImmediately:NO];
[con scheduleInRunLoop:[NSRunLoop currentRunLoop]
forMode:NSRunLoopCommonModes];
[con start];
If you are familiar with php I wrote a tutorial on using the google readi api recently.
http://mobile.tutsplus.com/tutorials/mobile-web-apps/building-a-mobile-web-application-with-the-google-reader-api/
One thing I notice is that in this string
http://www.google.com/reader/api/0/edit-tag/a=user/-/state/com.google/read&async=true&s=feed/%#&i=%#
Your not including the "edit" token the url should look like this. and you need the ? after edit-tag.
http://www.google.com/reader/api/0/edit-tag?a=user/-/state/com.google/read&async=true&s=feed/%#&i=%#&T=%#
You can get the "edit" token from this link once you have the user logged in, https://www.google.com/reader/api/0/token
Sorry can't help with objective-c stuff.