我想将一个 JSON 值“发布”到服务器并响应一个 json 数据回传。
URL:http ://solok.com:8080/soloo/phone/execute?content= {"method":"tet_123","version","1"},可以在浏览器中获取正确的值(JSON)。
ASIHTTPRequest 方式:
NSDictionary *postDic = [NSDictionary dictionaryWithObjectsAndKeys:@"tet_123",@"method",@"1",@"version",nil];
NSString *postString;
//Then convert the "postDic" to NSString, the value is:{"method":"tet_123","version","1"} assign to postString;
psotString = ...;
ASIFormDataRequest *req=[ASIFormDataRequest requestWithURL:url];
[req setRequestMethod:@"POST"];
[req setPostValue:posStr forKey:@"content"];
[req startAsynchronous];
[req setDelegate:self];
[req setCompletionBlock:^{
NSData *d = [req responseData];
NSLog(@"respond is %@".d);
}
它工作顺利!但是AFNetworkding不是,这里是代码;
NSURL *url = [NSURL URLWithString:@"http://localhost:8080"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
[httpClient setParameterEncoding:AFJSONParameterEncoding];
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"tet_123",@"method",@"1",@"version",nil];
NSDictionary *dic1 = [NSDictionary dictionaryWithObjectsAndKeys:dic,@"content", nil];
[httpClient postPath:@"/soloo/phone/execute" parameters:dic1 success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSDictionary *d = (NSDictionary *)responseObject;
NSLog(@"success is %@",d);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"fail");
}];
输出是:成功是<>。
或者我使用另一种 AFNetworking 方式:
NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST"path:@"/soloo/phone/execute" parameters:dic1];
AFJSONRequestOperation *ope = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(@"response %d",response.statusCode);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(@"fail%d JSON %@",response.statusCode,JSON);
}];
响应码是 200,表示连接正确,但仍然没有正确的结果。不知道为什么。任何帮助,提前感谢!