Problem with REST API on iPhone
I'm working on an iPhone app that will interact with a web service using RESTful API. I use NSURLConnection to do the work. The network code was working very well for all my needs until today.
For an instance, the URL(exclude the site) is like this:
/Listing/SearchAd?page=1&sortBy=DateDesc&q=BMW&id_cate开发者_JS百科gory=3016&psize=20
If the "q" parameter (BMW in this example) is less than 3 characters, or remove the q parameter entirely, my app can get back the right data. But if the q has more than 3 characters it can only get back a legal json structure with empty data.
But the most weird thing is, if I use another testing app (Rested, a mac app for testing REST services) to test the same URL, it can get back all the right data. so it shouldn't be a problem of the service.
Some code from my app:
NSURL *url = [[NSURL alloc] initWithString:[urlStr stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
NSURLConnection *con = [NSURLConnection connectionWithRequest:req delegate:self];
if (con) {
NSMutableData *data = [[NSMutableData alloc] init];
self.responseData = data;
[data release];
} else {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
}
I used netcat and get the following result: (the Token field is used for authentication for the web service)
The request using Rested:
GET /Listing/SearchAd?page=1&sortBy=DateDesc&q=BMW&id_category=3016&psize=20 HTTP/1.1
Host: localhost:2000
User-Agent: Rested/1.3 CFNetwork/520.0.13 Darwin/11.0.0 (x86_64) (MacBookPro7%2C1)
Accept: */*
Token: {E53D7DED-510A-414D-824D-3433077CF064}
Accept-Language: zh-cn
Accept-Encoding: gzip, deflate
Connection: keep-alive
The request using my app:
GET /Listing/SearchAd?page=1&sortBy=DateDesc&q=BMW&id_category=3016&psize=20 HTTP/1.1
Host: localhost:2000
User-Agent: Pazar/1.0 CFNetwork/485.13.9 Darwin/11.0.0
Token: {E53D7DED-510A-414D-824D-3433077CF064}
Accept: */*
Accept-Language: en-us
Accept-Encoding: gzip, deflate
Connection: keep-alive
The raw data my app get for the request is only 37 bytes long. After conversion using SBJsonParser, it's only the root level dictionary with the data field empty.
What could possibly be wrong then?
Some debugging tips:
Use netcat -l -p 2000
and use http://localhost:2000/
as your endpoint to capture the raw request. Capture the request using Rested as well and compare the two.
Also, log your raw response to see what is really in it. Perhaps your JSON conversion has an issue.
EDIT
Since the requests seem identical lets go a step further: A logging proxy. Here is my favorite netcat proxy, which forwards localhost:3000 to localhost:2000 and logs to infile and outfile. Modify as needed and test again with Rested and your app to see what really comes back.:
mkfifo proxypipe
cat proxypipe | nc -l -p 3000 | tee -a inflow | nc localhost 2000 | tee -a outflow 1>proxypipe
精彩评论