0

我正在使用 NSURLConnection 和 NSURLRequest 将一些 XML 数据的 HTTP POST 发送到服务器。

但是,服务器无法在 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

在这里,我在 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 *产品;

       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 回答