I am create one comment screen with one textFileds and buttons when I enter some text in textfield and press buttons that text should post on my sever . my request is started but my textField value not display . give me this message.
2014-10-31 14:01:29.314 SMSProject[5894:137428] request started...
2014-10-31 14:01:29.922 SMSProject[5894:137428] Response 200 : "Invalid Request"
I am using this API.
-(void)sendRequest
{
deatilinfoarray = [[NSMutableArray alloc] init];
NSURL *url = [NSURL URLWithString:
#"http://sms.instatalkcommunications.com/apireq/AddCommentForSMS"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setRequestMethod:#"POST"];
[request setPostValue:#"Id" forKey:#"Id"];
[request setPostValue:commenttext forKey:#"Comment"];
[request setPostValue:#"Author" forKey:#"Author"];
[request setPostValue:#"SMSId" forKey:#"SMSId"];
[request setPostValue:#"CreatedDate" forKey:#"CreatedDate"];
[request setDelegate:self];
[request startAsynchronous];
}
- (void) requestFinished:(ASIHTTPRequest *)request
{
NSLog(#"Response %d : %#", request.responseStatusCode, [request responseString]);
//NSData *responseData = [request responseData];
}
- (void) requestStarted:(ASIHTTPRequest *) request
{
NSLog(#"request started...");
}
- (void) requestFailed:(ASIHTTPRequest *) request
{
NSError *error = [request error];
NSLog(#"%#", error);
}
- (IBAction)btnpost:(id)sender
{
[self sendRequest];
}
I am not getting how to code for that please suggest me.
Try This:
Reference:
Tutorial
ASIHttpRequest POST
Source:
code
Related
This is the code Im using for ASIHTTPRequest I want to convert this to AFNetworking
NSURL *url = [NSURL URLWithString:path];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setRequestMethod:#"POST"];
[request addPostValue:self.theNewJob.jobID forKey:#"form[job_id]"];
[request addPostValue:thisJTF.typeFieldID forKey:#"form[jtf_id]"];
[request setFile:fullPath forKey:#"form[userfile]"];
[request startSynchronous];
NSError *error = [request error];
if (!error) {
NSString *response = [request responseString];
if ([response isEqualToString:#"SUCCESS"]) {
// debugger
NSLog(#"signature file uploaded");
} else {
// debugger
NSLog(#"signature file upload Fail: %# response: %#", error, response);
}
}
You need to replace all methods manually. I looked for it and I think below link is good to start: http://door3.com/insights/ios-programming-converting-asihttprequest-afnetworking
Hi im trying to make a POST request
my code:
NSURL *url = [NSURL URLWithString:urlString];
__weak ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setDelegate:self];
[request setRequestMethod:#"POST"];
[request setPostValue:#"JustinBieber" forKey:#"fname"];
[request setCompletionBlock:^{
NSString *result = [request responseString];
NSDictionary *dict = [result JSON];
NSLog(#"dict -%#",dict);
}];
[request setFailedBlock:^{
NSLog(#"error %#",[request error]);
}];
[request startAsynchronous];
when I run my code it returns a (null) value. My urlString is correct and the request didn't give me error also. I've tried it on web and returns a {"status":"success"} (it will return a dictionary with status successful or failed).
Use Like this. Hope this will help.
-(void)exe method
{
NSString *strURL=#"---your URL----";
NSURL *url=[NSURL URLWithString:strURL];
ASIFormDataRequest *request = [[ASIFormDataRequest alloc] initWithURL:url];
[request setRequestMethod:#"POST"];
[request setPostValue:#"JustinBieber" forKey:#"fname"];
[request setDelegate:self];
[request setTimeOutSeconds:60];
[request startAsynchronous];
}
- (void)requestFinished:(ASIHTTPRequest *)request
{
NSError *error;
if(!error)
{
NSString *receivedString = [request responseString];
NSDictionary *dic = [receivedString JSONValue];
NSLog(#"output %#",dic);
}
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
}
Try with this code -
NSURL *url = [NSURL URLWithString:urlString];
__unsafe_unretained ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setRequestMethod:#"POST"];
[request setPostValue:#"JustinBieber" forKey:#"fname"];
[request setDelegate:self];
__block id jsonData;
[request setTimeOutSeconds:300];
[request setCompletionBlock:^(){
NSError *error = nil;
NSString *responseString = (request.responseString.length)?request.responseString:#"";
NSLog(#"%#",responseString);
NSData *responseData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
jsonData = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
if(error)
completionBlock(nil, error, task);
else
completionBlock(jsonData, error, task);
}];
[request setFailedBlock:^{
completionBlock(nil, request.error, task);
}];
[request startAsynchronous];
Might be it will helpfull for you.
Did you set your headers in the script that returns JSON correctly? Assuming you're using PHP:
header('Content-Type: application/json');
The default MIME-type is "text/plain", instead of "application/json". If you dont set the MIME-type correctly you're basicly trying to parse the whole document.
So instead of:
{"status":"success"}
You are most likely trying to parse:
<html>
<head></head>
<body>{"status":"success"}</body>
</html>
-(void)exe method
{
NSString *strURL=#"---your URL----";
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:strURL]];
[request setDelegate:self];
[request setRequestMethod:#"POST"];
[request setPostValue:#"JustinBieber" forKey:#"fname"];
[request setTimeOutSeconds:60];
[request startAsynchronous];
}
- (void)requestFinished:(ASIHTTPRequest *)request
{
NSString *receivedString = [request responseString];
NSLog(#"output %#",receivedString );
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
NSString *receivedString = [request responseString];
NSLog(#"output %#",receivedString );
}
my problem is I cannot send the text messages to server. Im using asihttprequest. I have define the USERNAME, UUID, PASSWORD, API_PASSWORD and NUMBER myself. What I want to do is just send the data to the server url given. Here is my code:
- (IBAction)sendClicked:(id)sender {
[sendButton resignFirstResponder];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:#"https://cc.frifon.net_dosmssend/"]];
[request setDelegate:self];
[request setNumberOfTimesToRetryOnTimeout:3];
[request setRequestMethod:#"POST"];
[request setPostValue:USERNAME forKey:#"sip"];
[request setPostValue:PASSWORD forKey:#"pwd"];
[request setPostValue:UUID forKey:#"uuid"];
[request setPostValue:API_PASSWORD forKey:#"key"];
[request setPostValue:messageText forKey:#"message"];
[request setPostValue:NUMBER forKey:#"to"];
[request setPostValue:#"Submit" forKey:#"submit"];
[request start];
nil;
[request startAsynchronous];
}
- (void)requestFinished:(ASIHTTPRequest *)request {
NSError *error = [request error];
if (!error) {
NSString *response = [request responseString];
messageText.text = response;
}
}
Try this,
- (IBAction)sendClicked:(id)sender {
[sendButton resignFirstResponder];
NSString *serviceString = https://cc.frifon.net_dosmssend/;
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:[serviceString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]]];
[request setDelegate:self];
request.requestMethod = #"POST";
request.timeOutSeconds = 30.0;
[request addPostValue:USERNAME forKey:#"sip"];
[request addPostValue:PASSWORD forKey:#"pwd"];
[request addPostValue:UUID forKey:#"uuid"];
[request addPostValue:API_PASSWORD forKey:#"key"];
[request addPostValue:messageText forKey:#"message"];
[request addPostValue:NUMBER forKey:#"to"];
[request addPostValue:#"Submit" forKey:#"submit"];
[request startAsynchronous];
}
- (IBAction)sendClicked:(id)sender {
// Add you all data in below dictionary
NSDictionary *dictionary = #{#"action":#"login",#"nick_name":nikname,#"password":pass};
NSError *error;
NSData *data = [NSJSONSerialization dataWithJSONObject:dictionary options:0 error:&error];
NSString *jason =[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"JSON summary: %#", jason);
NSString *address = [NSString stringWithFormat:#"%#",#"www.demo.com"];
address= [address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *URL = [NSURL URLWithString:address];
NSLog(#"%#",address);
// request creation
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL cachePolicy:NSURLCacheStorageAllowedInMemoryOnly
timeoutInterval:60.0];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPBody:data];
responseData = [[NSMutableData alloc] init];
NSURLConnection *Conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[Conn start];
}
I am at a loss here, I thought I'd try something new with web services for my app.
I can pull data down no problem, but I am trying to post to the server and just can seem to get this to even fire.
What I am intending to happen is on submit button press the action be fired:
- (IBAction)didPressSubmit:(id)sender {
//JSON SERIALIZATION OF DATA
NSMutableDictionary *projectDictionary = [NSMutableDictionary dictionaryWithCapacity:1];
[projectDictionary setObject:[projectName text] forKey:#"name"];
[projectDictionary setObject:[projectDescShort text] forKey:#"desc_short"];
[projectDictionary setObject:[projectDescLong text] forKey:#"desc_long"];
NSError *jsonSerializationError = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:projectDictionary options:NSJSONWritingPrettyPrinted error:&jsonSerializationError];
if(!jsonSerializationError) {
NSString *serJSON = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"Serialized JSON: %#", serJSON);
} else {
NSLog(#"JSON Encoding Failed: %#", [jsonSerializationError localizedDescription]);
}
// JSON POST TO SERVER
NSURL *projectsUrl = [NSURL URLWithString:#"http://70.75.66.136:3000/projects.json"];
NSMutableURLRequest *dataSubmit = [NSMutableURLRequest requestWithURL:projectsUrl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
[dataSubmit setHTTPMethod:#"POST"]; // 1
[dataSubmit setValue:#"application/json" forHTTPHeaderField:#"Accept"]; // 2
[dataSubmit setValue:[NSString stringWithFormat:#"%d", [jsonData length]] forHTTPHeaderField:#"Content-Length"]; // 3
[dataSubmit setHTTPBody: jsonData];
[[NSURLConnection alloc] initWithRequest:dataSubmit delegate:self];
}
After that it runs through:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(#"DidReceiveResponse");
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)theData
{
NSLog(#"DidReceiveData");
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
UIAlertView *errorView = [[UIAlertView alloc] initWithTitle:#"Error" message:#"BLAH CHECK YOUR NETWORK" delegate:nil cancelButtonTitle:#"Dismiss" otherButtonTitles:nil];
[errorView show];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
I am obviously missing something, but I don't even know where to look. All I need is a point in the right direction, any help would be great.
UPDATE
I was able to get the request to fire with the following.
Okay I was able to get the request to fire using the following:
- (IBAction)didPressSubmit:(id)sender {
NSMutableDictionary *projectDictionary = [NSMutableDictionary dictionaryWithCapacity:1];
[projectDictionary setObject:[projectName text] forKey:#"name"];
[projectDictionary setObject:[projectDescShort text] forKey:#"desc_small"];
[projectDictionary setObject:[projectDescLong text] forKey:#"desc_long"];
NSError *jsonSerializationError = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:projectDictionary options:NSJSONWritingPrettyPrinted error:&jsonSerializationError];
if(!jsonSerializationError) {
NSString *serJSON = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"Serialized JSON: %#", serJSON);
} else {
NSLog(#"JSON Encoding Failed: %#", [jsonSerializationError localizedDescription]);
}
NSURL *projectsUrl = [NSURL URLWithString:#"http://70.75.66.136:3000/projects.json"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:projectsUrl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
[request setHTTPMethod:#"POST"]; // 1
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"]; // 2
[request setValue:[NSString stringWithFormat:#"%d", [jsonData length]] forHTTPHeaderField:#"Content-Length"]; // 3
[request setHTTPBody: jsonData]; // 4
(void) [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
But for some reason the post method only received a bunch of nil values, I am getting this from the server side. Processing by ProjectsController#create as JSON
Parameters: {"{\n \"desc_long\" : \"a\",\n \"name\" : \"a\",\n \"desc_small\" : \"a\"\n}"=>nil}
UPDATE 2
With a little read from here: http://elusiveapps.com/blog/2011/04/ios-json-post-to-ruby-on-rails/
I was able to see if missed the following line.
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
So final didPressSubmit code is as follows;
- (IBAction)didPressSubmit:(id)sender {
NSMutableDictionary *projectDictionary = [NSMutableDictionary dictionaryWithCapacity:1];
[projectDictionary setObject:[projectName text] forKey:#"name"];
[projectDictionary setObject:[projectDescShort text] forKey:#"desc_small"];
[projectDictionary setObject:[projectDescLong text] forKey:#"desc_long"];
NSError *jsonSerializationError = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:projectDictionary options:NSJSONWritingPrettyPrinted error:&jsonSerializationError];
if(!jsonSerializationError) {
NSString *serJSON = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"Serialized JSON: %#", serJSON);
} else {
NSLog(#"JSON Encoding Failed: %#", [jsonSerializationError localizedDescription]);
}
NSURL *projectsUrl = [NSURL URLWithString:#"http://70.75.66.136:3000/projects.json"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:projectsUrl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
[request setHTTPMethod:#"POST"]; // 1
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"]; // 2
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [jsonData length]] forHTTPHeaderField:#"Content-Length"]; // 3
[request setHTTPBody: jsonData]; // 4
(void) [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
I got same issue but I resolved it by setting the options to nil.
Replace
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:projectDictionary options:NSJSONWritingPrettyPrinted error:&jsonSerializationError];
by
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:projectDictionary options:nil error:&jsonSerializationError];
Use option to nil if you are sending json to server, if you are displaying json use NSJSONWritingPrettyPrinted.
Hope this will help you.
When I NSLog HTTP requests response string, it appears as "ãÃÂïãÃâ¬ÃÂãÃÂÃâãÃÂ" and something different appears on UILabel but not the same as I expect in Japanese/Chinese format. I am using ASIHTTPRequest and as mentioned here I have set response encoding to NSUTF8StringEncoding(server uses UTF-8 same) but it didn't help. Could someone please tell me how to support unicode character in my App? Thanks.
- (void)getData
{
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:[dataUrl stringByAppendingFormat:#"%#",self.selectedID]]];
[request setResponseEncoding:NSUTF8StringEncoding];
SBJSON *parser = [[SBJSON alloc] init];
NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithCapacity:3];
[data setObject:self.username forKey:#"username"];
[data setObject:self.password forKey:#"password"];
NSString *dataJSON = [parser stringWithFragment:data error:nil];
[request appendPostData:[dataJSON dataUsingEncoding:NSUTF8StringEncoding]];
[request setDelegate:self];
[request setDidFinishSelector:#selector(requestSuccess:)];
[request setDidFailSelector:#selector(requestFailed:)];
[self.queue addOperation: request];
[self.queue go];
}
- (void)requestSuccess:(ASIHTTPRequest *)request
{
NSLog(#"success: %#", [request responseString]);
}
I managed to fix this. Following is the change!
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:[dataUrl stringByAppendingFormat:#"%#",self.selectedID]]];
[request setResponseEncoding:NSUTF8StringEncoding]; -- > Wrong!!!
request.defaultResponseEncoding = NSUTF8StringEncoding; --> Correct!