2012-03-23 74 views
0

我想「POST」一個JSON值給服務器並響應一個json數據包。ASIHttpRequest POST JSON不錯,但AFNetworking不是

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,這意味着連接是正確的,但仍然沒有正確的結果。 不知道爲什麼。任何幫助,提前感謝!

回答

0

原因是後端是一個「GET」方法,但我做了「POST」,與此同時,我忘了:[Operation start]方法。