0

NSURLConnection と NSURLRequest を使用して、サーバーへの XML データの HTTP POST を実行しています。

ただし、Web ページがフォーム送信を行っていると仮定してパッケージ化されているため、サーバーは HTTP 本文でデータを見つけることができません (パラメーター = form-urlencoded が設定されています。おそらくデフォルトでは NSURLConnection? によって)。

これは私が明示的に行っていることではなく、次を使用して本体データを追加するだけです。

  [request setHTTPBody: [body dataUsingEncoding:NSUTF8StringEncoding]];

この動作を停止/オーバーライドするにはどうすればよいですか?

4

2 に答える 2

0

デフォルト値はわかりませんが、次のように変更できます。

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

ドキュメントをご覧ください。

于 2012-05-08T20:58:34.263 に答える
0

ここでは、XML データを Web サーバーに投稿し、NSURLConnection を使用して xml 応答を取得しています。手順は次のとおりです。

1) NSURLConnection 非同期リクエストを介してサーバーにデータを投稿する

    NSMutableString *productDetailString =[[NSMutableString alloc] init];

    [productDetailString appendString:@"<product>"];
    [productDetailString appendFormat:@"<product_name>%@</product_name>",name];
    [productDetailString appendString:@"<product_id>1024</product_id>"];
    [productDetailString appendString:@"</product>"];        


     NSString *message=[[NSString alloc] initWithFormat:@"_xmlrequestPostage=%@",productDetailString];


//    NSString *message=[[NSString alloc] initWithFormat:@"_xmlrequestPostage="                             
//                      "<product>\n"
//                          "<product_name>%@</product_name>\n"
//                          "<product_id>%@</product_id>\n"
//                      "</product>\n",name, id];


    NSString *urlString = [NSString stringWithFormat:@"http://flightsflights.com.au/Mega/product.asmx/GetProductPrice"];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
    [request setURL:[NSURL URLWithString:urlString]];
    [request setHTTPMethod:@"POST"];


    //set headers

    NSString *contentType = [NSString stringWithFormat:@"application/x-www-form-urlencoded"];
    [request addValue:contentType forHTTPHeaderField: @"Content-Type"];

    [request addValue:[NSString stringWithFormat:@"%d",[message length]] forHTTPHeaderField:@"Content-Length"];

    //create the body

    NSMutableData *postBody = [[NSMutableData alloc]initWithData:[[NSString stringWithFormat:@"%@",message] dataUsingEncoding:NSUTF8StringEncoding]];

    //post
    [request setHTTPBody:postBody];

    //get response
    NSURLConnection *connection=[[NSURLConnection alloc] initWithRequest:request delegate:self];

    if(connection)
    {
        webData=[[NSMutableData data] retain];
    }
    else
    {
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"Mega Australia" message:@"Problem in network." delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [alert show];
        [alert release];
    }

2) デリゲートに NSURLConnection クラスを通知する

    -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
    {
       [webData setLength: 0];
    }
   -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
    {
       [webData appendData:data];
    }
   -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
    {
         UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Error" message:@"ERROR with conenction " delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
        [alert show];
        [alert release];
    [connection release];
    [webData release];
    }
   -(void)connectionDidFinishLoading:(NSURLConnection *)connection
   {
        if(webData==nil)
        {
             UIAlertView *thealert=[[UIAlertView alloc] initWithTitle:@"Error" message:@"No data found." delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
            [thealert show];
            [thealert release];
        }
        else
        {

             NSString *str=[[NSString alloc] initWithData:webData encoding:NSUTF8StringEncoding];

            str=[str stringByReplacingOccurrencesOfString:@"&lt;" withString:@"<"];
            str=[str stringByReplacingOccurrencesOfString:@"&gt;" withString:@">"];

            NSData *data=[str dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
            product=[[NSMutableArray alloc] init];

            NSXMLParser *xmlParser=[[NSXMLParser alloc] initWithData:data];
            xmlParser.delegate=self;
            [xmlParser parse];
            webData=nil;
            [webData release];
       }
   }

3) .h ファイルに次の変数を追加します。NSMutableDictionary *aProduct; NSMutableArray *製品;

       NSMutableString *name, *pro_id, *currentElement, *statusCode;
   }
   @property (retain, nonatomic) NSMutableString *name;
   @property (retain, nonatomic) NSMutableString *pro_id;
   @property (retain, nonatomic) NSMutableString *statusCode;

4) .m ファイルの合成名、pro_id、および statusCode

5) NSXMLParse クラスのデリゲートに通知する

     -(void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
     {
           currentElement=[elementName copy];

           if([elementName isEqualToString:@"product"])
           {
              self.name=[[NSMutableString alloc] init];
              self.pro_id=[[NSMutableString alloc] init];

              aProduct=[[NSMutableDictionary alloc] init];
           }
           else if([elementName isEqualToString:@"status"])
           {
               self.statusCode=[[NSMutableString alloc] init];
           }
     }

     -(void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
     {
          if([currentElement isEqualToString:@"product_name"])
          {
               [self.name appendString:string];
          }
          else if([currentElement isEqualToString:@"product_id"])
          {
                [self.pro_id appendString:string];
          }
          else if([currentElement isEqualToString:@"status"])
          {
                [self.statusCode appendString:string];
                if(![self.statusCode isEqualToString:@"200"])
                {
                      UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"Mega Australia" message:@"Input string is not in a correct format." delegate:self cancelButtonTitle:@"Ok" otherButtonTitles: nil];
                      [alert show];
                      [alert release];
                      return;
                 }
           }
      }

      - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
      {
           if ([elementName isEqualToString:@"product"])
           {
                 [aProduct setObject:self.name forKey:@"name"];
                 [aProduct setObject:self.pro_id forKey:@"id"];

                 [product addObject:[aProduct copy]];
            }
      }

      - (void)parserDidEndDocument:(NSXMLParser *)parser
      {
            return;
      }
于 2013-02-27T09:40:56.047 に答える