2012-11-13 42 views
1

我想用JSON POST方法發佈一些數據到Web服務,我已經嘗試了很多方法來做到這一點,但沒有工作。這裏是我的代碼,請檢查:JSON POST不工作在iOs

NSArray *objects=[NSArray arrayWithObjects:@"value1", @"value2",@"value3", @"value4",@"value5", @"value6",@"value7", @"value8",@"value9", nil] ; 
    NSArray *keys=[NSArray arrayWithObjects:@"FirstName", @"LastName",@"UserName", @"Password",@"Email", @"Gender",@"DeviceId", @"DeviceName",@"ProfileImage", nil]; 

    NSData *_jsonData=nil; 
    NSString *_jsonString=nil; 
    NSURL *url=[NSURL URLWithString:urlstring]; 

    NSDictionary *JsonDictionary=[NSDictionary dictionaryWithObjects:objects forKeys:keys]; 

    if([NSJSONSerialization isValidJSONObject:JsonDictionary]){ 
     _jsonData=[NSJSONSerialization dataWithJSONObject:JsonDictionary options:0 error:nil]; 
     _jsonString=[[NSString alloc]initWithData:_jsonData encoding:NSUTF8StringEncoding]; 
    } 

    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url]; 
    [request setHTTPMethod:@"POST"]; 
// [request setHTTPBody:_jsonData]; 
// [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; 
// [request setValue:@"application/json" forHTTPHeaderField:@"Accept"]; 
// [request setValue:[NSString stringWithFormat:@"%d", [_jsonData length]] forHTTPHeaderField:@"Content-Length"]; 

    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; 

    NSString *finalString = [_jsonString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]; 

    [request setHTTPBody:[finalString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]]; 

    // //return and test 
    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; 
    NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding]; 

請檢查。

回答

1

請求應該是沿着這些路線的東西...

NSURL * url = [NSURL URLWithString:@"your_url"]; 
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url]; 
[request setHTTPMethod:@"POST"]; 
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; 

NSError * error = nil; 
NSData * postData = [NSJSONSerialization dataWithJSONObject:your_json_dictionary_here options:NSJSONReadingMutableContainers error:&error]; 
[request setHTTPBody:postData]; 

我也建議檢查你的反應,找出爲什麼你的請求失敗。它是在客戶端還是服務器端(以及爲什麼?)...

+0

當我提交服務器,在它顯示的服務器上,缺少'{'和'}'。 – Mithuzz

+0

@Mithuzz由於您沒有提供任何有關後端基礎架構的信息,因此無法提供更多幫助。請求到達服務器的事實更多地指向那裏有問題,而不是在客戶端。 –

+0

只是要清楚,在你的代碼中,你沒有爲「NSJSONSerialization」設置選項嗎? –

3

以下是試圖註冊用戶的示例代碼。 在「註冊」按鈕,點擊,寫了下面的代碼:

- (IBAction)registerButtonPressed:(id)sender 
{ 
    BOOL valid = FALSE; 
    valid=[self validateEntry]; 
    if(valid) 
    { 
    NSString *bytes = [NSString stringWithFormat:@"{\"UserName\":\"%@ %@\",\"Email\":\"%@\",\"UserType\":\"normaluser\",\"Password\":\"%@\"}",firstName,lastName,email,password]; 
    NSURL *url=[NSURL URLWithString:urlstring]; 
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 
    [request setHTTPMethod:@"POST"]; 
    [request setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"]; 
    [request setHTTPBody:[bytes dataUsingEncoding:NSUTF8StringEncoding]];   
    [self setUrlConnection:[NSURLConnection connectionWithRequest:request delegate:self]]; 
    [self setResponseData:[NSMutableData data]]; 
    [self.urlConnection start]; 
    } 
} 

然後添加下面的連接委託方法:

- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{ 
    [self.responseData setLength:0]; 
} 

- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{  
    [self.responseData appendData:data]; 
} 
- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{ 
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO; 
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Network Status" 
               message:@"Sorry,Network is not available. Please try again later." 
               delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil]; 
    [alert show]; 

} 
- (void) connectionDidFinishLoading:(NSURLConnection *)connection 
{ 
    if (connection == self.urlConnection) 
    { 
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;   
    NSError *error;   
    NSDictionary *jsonString=[NSJSONSerialization JSONObjectWithData:self.responseData options:kNilOptions error:&error];   
    if(jsonString != nil) 
    {   
     if ([[[jsonString objectForKey:@"data"] objectForKey:@"id"] length]) 
     { 
      [[NSUserDefaults standardUserDefaults] setValue:[[jsonString objectForKey:@"data"] objectForKey:@"id"] forKey:@"user_id"]; 
      [[NSUserDefaults standardUserDefaults] setValue:[[jsonString objectForKey:@"data"] objectForKey:@"UserName"] forKey:@"user_name"];     
      [[NSUserDefaults standardUserDefaults] synchronize]; 
      [delegate userRegistrationViewControllerResponse:self]; 
     } 
     else 
     { 
      UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:@"Info" message:[jsonString objectForKey:@"statusText"] delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil]; 
      [alertView show]; 
     } 
    } 
    else 
    { 
     UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:@"Server Busy" message:@"Register after sometime" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil]; 
     [alertView show]; 
    } 
    } 
} 
  • 這將發佈的用戶信息作爲JSON。
2

試試這個....

NSURL *aUrl = [NSURL URLWithString:@"https://www.website.com/_api/Login/"]; 
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl 
                 cachePolicy:NSURLRequestUseProtocolCachePolicy 
                 timeoutInterval:0.0]; 
[request setHTTPMethod:@"POST"]; 
NSString *postString = [NSString stringWithFormat:@"EmailAddress=%@&UserPassword=%@",uName.text,pwd.text]; 
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]]; 
[[NSURLConnection alloc] initWithRequest:request delegate:self]; 

-Than調用NSURLConnection的委託方法..點忘記的Alloc的responseData ....

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { 
[responseData appendData:data]; 
} 

- (void)connectionDidFinishLoading:(NSURLConnection *)connection { 
[connection release]; 
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; 
responseData = nil; 
json =[[responseString JSONValue] retain]; 
NSLog(@"Dict here: %@", json); 
}