我想将一个JSON值“POST”到服务器并响应一个json数据包。
网址: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");
}];
输出为:success is<>。
或者我使用另一种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,表示连接正确,但仍然没有正确的结果。 不知道为什么。任何帮助,谢谢!
答案 0 :(得分:0)
原因是后端是一个“GET”方法,但我做了“POST”,同时,我忘了:[操作开始]方法。