NSURLConnection / NSURLRequest默认将POST设置为表单提交?

时间:2012-05-08 20:17:13

标签: ios

我正在使用NSURLConnection和NSURLRequest对服务器执行某些XML数据的HTTP POST。

然而,服务器无法在HTTP正文中找到数据,因为假设网页正在进行表单提交(参数= form-urlencoded正在设置,大概默认为NSURLConnection?),它已被打包。

这不是我明确做的事情,我只是使用以下方法添加正文数据:

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

如何停止/覆盖此行为?

2 个答案:

答案 0 :(得分:0)

我不知道默认值,但您可以使用以下命令进行更改:

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

查看documentation

答案 1 :(得分:0)

在这里,我在Web服务器上发布XML数据并使用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文件中添加以下变量:        {            NSMutableData * webData;            NSMutableDictionary * aProduct;            NSMutableArray * product;

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