how to post json data by using asihttprequest
asihttprequest, ios, json
Solution
You can post text data in json format like this
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setRequestMethod:@"POST"];
[request addRequestHeader:@"Accept" value:@"application/json"];
[request addRequestHeader:@"content-type" value:@"application/x-www-form-urlencoded"];
[request addRequestHeader:@"User-Agent" value:@"iPad"];
API itself sets user-agent although you can set it yourself too
request.allowCompressedResponse = NO;
request.useCookiePersistence = NO;
request.shouldCompressRequestBody = NO;
[request setPostBody:[NSMutableData dataWithData:[jsonRequest dataUsingEncoding:NSUTF8StringEncoding]]];
[request startSynchronous];
Problem
I intend to post json data : ``` NSString *newJSON = [theDictionary JSONRepresentation]; NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:ADDRESS,action]]; ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url]; [request appendPostData:[newJSON dataUsingEncoding:NSUTF8StringEncoding]]; [request startSynchronous]; NSString *responseString = [request responseString]; NSMutableDictionary* responseDict = [responseString JSONValue]; NSLog(@"responseString = %@",responseString); ``` does the code work?did I miss some code? I read the asihttprequest tutorial,and find it always post data with asiformdatarequest,what's the difference between asihttprequest and asiformdatarequest,if I just want to post json data,what should I do?thank you in advance. UPDATE:yes,it works,but don't work well,I use some tool test the data,and receive some extra data: ``` POST / HTTP/1.1 Host: 192.168.0.113 User-Agent: Ushi.com/1.0 CFNetwork/548.1.4 Darwin/11.3.0 Content-Length: 58 ```