1

JSON POST メソッドを使用して Web サービスにデータを投稿しようとしています。これを行うために非常に多くの方法を試しましたが、どれも機能していません。これが私のコードです。確認してください:

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

チェックしてください。

4

3 に答える 3

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];
  }
}

次に、次を Connection デリゲート メソッドとして追加します。

   - (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 として投稿されます。
于 2012-11-13T11:49:12.273 に答える
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];

また、リクエストが失敗した理由を確認するために、レスポンスを確認することをお勧めします。それはクライアント側ですか、それともサーバー側ですか (そしてその理由は?)...

于 2012-11-13T10:51:02.667 に答える