I need to pass some data in order for the server to the save the info,in order to do this the parameters need to pass the parameters in XML nodes following a url http://xxx.xxx.xx.xxx/WCF/Service1.svc/XXX/Upload?sXML=
Here is an example of the XML node structure
<Send_info>
<Service_order>
</Service_order>
<Data_stream>
<info>
</info>
</Data_stream>
</Send_info>.
The return value would be a JSON string with {"Uploaded":"TRUE"} or {"Uploaded":"FALSE"} respectively.
I have tried this method with no answer it just return nil.
-(void)Request:(NSData*)data{
NSURL *aUrl = [NSURL URLWithString:#"http://xxx.xxx.xx.xxx/WCF/Service1.svc/XXX/Upload?sXML="];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request setHTTPMethod:#"GET"];
[request setHTTPBody:data];
NSURLConnection *connection= [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
}
edit:you can find the answer in the comments
The answer was quite simple just use these blocks of code and substitute them with your own parameters
POST:
-(void)webservicepost:(NSString *)poststring{
NSString *poststring = #"String in the format we need to upload";
NSURL *remoteURL = [NSURL URLWithString:#"URL in which we'll upload"];
NSMutableURLRequest *Request = [[NSMutableURLRequest alloc] initWithURL:remoteURL];
[Request addValue:#"application/json; charset=utf-8" forHTTPHeaderField: #"Content-Type"];//Formats for the data
NSMutableData *body = [NSMutableData data];
[body appendData:[poststring dataUsingEncoding:NSUTF8StringEncoding]]; //Add content and coding
[Request setHTTPMethod:#"POST"]; //POST method
[Request setHTTPBody:body];
NSData *data = [NSURLConnection sendSynchronousRequest:Request returningResponse:nil error:nil];//Server response in data form
NSString *sdata = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];//Server response in string form
}
GET:
-(void)get:(NSString *)myxmlstring{
NSString *escapedString = [myxmlstring stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *urlString = [NSString stringWithFormat:#"http://xxx.xxx.xx.xxx/WCF/Service1.svc/XXX/Upload?sXML=%#",escapedString];
NSURL *url = [NSURL URLWithString:urlString];
NSData *data = [NSURLConnection sendSynchronousRequest:Request returningResponse:nil error:nil];//Server response in data form
NSString *sdata = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];//Server response in string form
//FROM HERE YOU CAN USE THE RETRIEVED INFORMATION FROM THE URL
}
Related
I am using two links.First link i created nsaaray for "id".This "id" i need to pass as parameter in nsurlconnection using POST method by second link.i tried lots but i stuck in while passing parameter "id".
nsaaray for id:
- (IBAction)button_drop:(id)sender {
NSString *parseURL =#"first_link";
NSString *encodeurl =[parseURL stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:encodeurl];
NSData *data = [NSData dataWithContentsOfURL:url];
if(data){
NSError *error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options: kNilOptions error:&error];
arrMsg = [json valueForKeyPath:#"Branches.branch_name"];
arrmsg1 =[json valueForKeyPath:#"Branches.id"];
[_picker2 reloadAllComponents];
}
}
POST method using nsurlconnection:
NSString *Branchid=#"3";
NSURL *url = nil;
NSMutableURLRequest *request = nil;
if([method isEqualToString:#"GET"]){
NSString *getURL = [NSString stringWithFormat:#"%#?branch_id=%#\n", URL, Branchid];
url = [NSURL URLWithString: getURL];
request = [NSMutableURLRequest requestWithURL:url];
NSLog(#"%#",getURL);
}else{ // POST
NSString *parameter = [NSString stringWithFormat:#"branch_id=%#",Branchid];
NSData *parameterData = [parameter dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
url = [NSURL URLWithString: URL];
NSLog(#"%#", parameterData);
request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPBody:parameterData];
arr= [NSMutableString stringWithUTF8String:[parameterData bytes]];
}
[request setHTTPMethod:method];
[request addValue: #"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if( connection )
{
mutableData = [NSMutableData new];
}
Try to create a "POST" method like this:-
NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:
Branchid, #"branch_id", nil];
NSString *newRequest = [dict JSONRepresentation];
NSData *requestData = [newRequest dataUsingEncoding:NSUTF8StringEncoding];
//If you are not using SBJsonParser Library then try the following:
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *urlString = #"YOUR URL String";
NSURL *requestURL = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:requestURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long) [requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:requestData];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection) {
mutableData = [NSMutableData new];
}
Also, You can follow this link if you don't find out the answer working properly:-
Data in POST or GET methods
Send data in POST methods
I'm trying to post to a webserver in iOS but am receiving a 404 error. The person I'm working with is able to post from a different system with the address and data in a single string:
http://xxx.xxx.xxx.xxx/api/message?salu=mr&firstname=john&lastname=smith&email=smith#testemail.com&country=usa&zipcode=99999&checkbox=y&messagelist=message&q1=1&q2=2&q3=3&q4=4&q5=5
I'm trying to do the same with the following code in Xcode:
NSString *body = [NSString stringWithFormat:#"message?salu=mr&firstname=john&lastname=smith&email=matt#testmail.com&country=usa&zipcode=99999&checkbox=y&messagelist=message&q1=1&q2=2&q3=3&q4=4&q5=5"];
NSData *data = [body dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [data length]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://xx.xxx.xxx.xxx/api"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:data];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *reply = [[NSString alloc] initWithBytes:[responseData bytes] length:[responseData length] encoding:NSASCIIStringEncoding];
NSLog(#"requestReply: %#", reply);
and the last few lines of 'reply' above from NSLog are:
<b> Description: </b>HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
<br><br>
<b> Requested URL: </b>/api<br><br>
</body>
However, I'm able to perform a 'GET' on the same address with the following code, where I receive the expected data:
NSMutableURLRequest *request2 = [[NSMutableURLRequest alloc] init];
[request2 setURL:[NSURL URLWithString:#"http://xx.xxx.xxx.xxx/api/message"]];
[request2 setHTTPMethod:#"GET"];
NSURLResponse *requestResponse;
NSData *requestHandler = [NSURLConnection sendSynchronousRequest:request2 returningResponse:&requestResponse error:nil];
NSString *requestReply = [[NSString alloc] initWithBytes:[requestHandler bytes] length:[requestHandler length] encoding:NSASCIIStringEncoding];
NSLog(#"requestReply: %#", requestReply);
So the web server is functioning and it appears the problem lies in the way I'm posting. Does anyone have an idea of what I'm doing wrong?
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://xx.xxx.xxx.xxx/api"]];
Don't you notice that you should call NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://xx.xxx.xxx.xxx/api/message"]];
/message is part of path, not request body.
and look forward to use some ready framework, such as AFNetworking is.
You've taken the last path component of the request's URL, message, and put that into the body of the request. So, replace:
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://xx.xxx.xxx.xxx/api"]];
with
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://xx.xxx.xxx.xxx/api/message"]];
Also, replace:
NSString *body = [NSString stringWithFormat:#"message?salu=mr&firstname=john&lastname=smith&email=matt#testmail.com&country=usa&zipcode=99999&checkbox=y&messagelist=message&q1=1&q2=2&q3=3&q4=4&q5=5"];
with:
NSString *body = [NSString stringWithFormat:#"salu=mr&firstname=john&lastname=smith&email=matt#testmail.com&country=usa&zipcode=99999&checkbox=y&messagelist=message&q1=1&q2=2&q3=3&q4=4&q5=5"];
// Web service request
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 ];
//returndata is response of webservice
NSString *responseString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];
NSDictionary *results = [responseString JSONValue] ;
NSLog(#"chat data- %#",results);
NSString *strResults = [results objectForKey:#"d"];
NSLog(#"result string is-%#",strResults);
this is the code that I am using for my Data fetching from web service. But i have to do this every time when come to this page.
Is that any method that can store my data in Cache memory so i need not to request every time.
I Am using
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
but i dont know how to use - (NSCachedURLResponse *) connection this method
thanks...
You need to use cache as of your needs according to this documentation: whenever you requesting a NSMutableURLRequest...
For Ex:
[NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString] cachePolicy:NSURLRequestReloadRevalidatingCacheData timeoutInterval:60];
For More details Kindly look into the Documentation
I think the title explains it. I can reach the Get functions on my api controllers just fine. I can reach the Post method, but my parameter (macAddress) is null. I've tried many variations of this code in xcode:
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#%#",baseURL,controller]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request setHTTPMethod:#"POST"];
NSString *postString = #"macAddress=testestest";
NSData *myRequestData = [ NSData dataWithBytes: [ postString UTF8String ] length: [ postString length ] ];
[request setHTTPBody:myRequestData];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"content-type"];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
and the controller:
public String Post([FromBody]string macAddress)
{
//......
}
(I'm aware that I'm using synchronous requests and nil response/errors, just trying to figure out this aspect)
Thanks for the help.
It looks like you have your *postString without the [NSString stringWithFormat method]. I use the following code with my own restful API.
NSString *deviceToken = [[NSUserDefaults standardUserDefaults] objectForKey:#"rsdevicetoken"];
NSString *postString = [NSString stringWithFormat:#"token=%#&active=%#&draw=%#&result=%#&message=%#",deviceToken,allNotify, draw, results, message];
NSData *postData = [postString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://www.someurl.com/updateSubscriptions"]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:postData];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *data=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"%#", data);
Hopefully this will help you.
It's a wild guess but if your macAddress post param has the following format: 01:23:45:67:89:ab you need to url encode the ':' to '%3A'.
I have writen the fellowing code:
NSString *urlString = [NSString stringWithFormat:ADDRESS,action];
postStr = #"user_name=Thomas Tan&phone=01234567891&password=123456";
NSData *myRequestData = [NSData dataWithBytes:[postStr UTF8String] length:[postStr length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody: myRequestData];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *responseString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSLog(#"%#",responseString);
it works well,but now I want to use asihttprequest framework,so how to change the above code,I have writen the code,but it can't get the correct result and just get the server error infomation.so what's the problem?
NSString *urlString = [NSString stringWithFormat:ADDRESS,action];
NSURL *url = [NSURL URLWithString:urlString];
ASIFormDataRequest *requeset = [ASIFormDataRequest requestWithURL:url];
[requeset setRequestMethod:#"POST"];
[requeset setPostValue:#"Thomas Tan" forKey:#"user_name"];
[requeset setPostValue:#"01234567891" forKey:#"phone"];
[requeset setPostValue:#"123456" forKey:#"password"];
[requeset startSynchronous];
NSError *error = [requeset error];
if (!error) {
NSString *re = [requeset responseString];
NSLog(#"%#",re);
}
NSLog(#"%#",error);
thank you in advance.
UPDATE:
NSString *urlString = [NSString stringWithFormat:ADDRESS,action];
NSURL *url = [NSURL URLWithString:urlString];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setRequestMethod:#"POST"];
[request appendPostData:[#"user_name=Thomas Tan&phone=01234567891&password=123456" dataUsingEncoding:NSUTF8StringEncoding]];
[request startSynchronous];
NSError *error = [request error];
if (!error) {
NSString *re = [request responseString];
NSLog(#"%#",re);
}
NSLog(#"%#",error);
I use the above code ,It also can't get the same result,and error is not nil.
Your ASIHTTP code is not doing the same thing as your NSURLConnection code.
ASIFormDataRequest will automatically:
set the Content-Type header to application/x-www-form-urlencoded
URL-encoded your parameters
That's usually exactly what you want, but if you're getting the correct behavior with your NSURLConnection code and incorrect with ASIHTTP, then you need to change to a custom ASIHTTP POST and use ASIHTTPRequest, not ASIHTTPFormDataRequest, and then manually set the Conten-type back to application/x-www-form-urlencoded:
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setRequestMethod:#"POST"];
[request addRequestHeader:#"Content-Type" value:#"application/x-www-form-urlencoded"];
[request appendPostData:[#"user_name=Thomas Tan&phone=01234567891&password=123456" dataUsingEncoding:NSUTF8StringEncoding]];
Doing this, and inspecting exactly what was sent to the server using Wireshark, I can see that the POST data sent is still not quite identical (ASIHTTP on the left, NSURLConnection on the right):
But the content type, length, and actual data is identical.
At this point, I'd expect your server to return the same result.
If it still doesn't, you can edit the ASIhTTP request parameters to match.