2

我打算发布 json 数据:

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);

代码有效吗?我错过了一些代码吗?我阅读了asihttprequest教程,发现它总是用asiformdatarequest发布数据,asihttprequest和asiformdatarequest有什么区别,如果我只想发布json数据,我该怎么办?提前谢谢你。

更新:是的,它有效,但效果不佳,我使用一些工具测试数据,并收到一些额外的数据:

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
4

1 回答 1

7

您可以像这样以 json 格式发布文本数据

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 本身设置用户代理,尽管您也可以自己设置

request.allowCompressedResponse = NO;
request.useCookiePersistence = NO;
request.shouldCompressRequestBody = NO;
[request setPostBody:[NSMutableData dataWithData:[jsonRequest  dataUsingEncoding:NSUTF8StringEncoding]]];
[request startSynchronous];
于 2012-10-15T08:51:46.477 回答