用Post方法+ iphone解析xml

时间:2011-09-21 06:30:35

标签: iphone nsxmlparser nsmutableurlrequest

我遇到了使用post方法的xmlparsing问题。

API URL :  http://XXX.XXX.X.XX/api/user.php
Function Name : getUserList
Sample XML :
<root>
    <data>
        <id>0</id>
        <search></search>
    </data>
</root>

现在我正在使用: -

// setting up the URL to post to
NSString *urlString = @"http://XXX.XXX.X.XX/api/user.php";

// setting up the request object now
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];        

但是我应该如何将HTML实体发布在此...

意味着我应该在代码

中放置函数名称和示例xml的位置和方式

我的编辑问题是 : -

  NSString *urlString = @" http://192.168.6.79/silverAPI/api/user.php/getUserList";

    // setting up the request object now
    NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
    [request setURL:[NSURL URLWithString:urlString]];
    [request setHTTPMethod:@"POST"];
    NSString * str = @"<root><data><id>0</id><search>a</search></data></root>";
    NSString * message= [NSString stringWithFormat:@"/getUserList mydata=%@", str];
    [request setHTTPBody:[message dataUsingEncoding:NSUTF8StringEncoding]];
    [request addValue:@"application/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];





    // now lets make the connection to the web
    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];

    NSLog(@"Responce==>%@",returnString);

但是我的回答是黑色的.Pleaseee帮我解决.. 是我的

 NSString *urlString = @" http://192.168.6.79/silverAPI/api/user.php/getUserList";

并且

  

NSString * str =   @ “0A”;       NSString * message = [NSString stringWithFormat:@“/ getUserList   mydata =%@“,str];       [请求setHTTPBody:[消息   dataUsingEncoding:NSUTF8StringEncoding]];       [请求addValue:@“application / xml; charset = utf-8”   forHTTPHeaderField:@ “内容类型”];

这段代码是正确的吗?

2 个答案:

答案 0 :(得分:1)

您可以使用方法- (void)setHTTPBody:(NSData *)data设置html正文。例如:

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

在哪种情况下,消息是xml。

此外,您还需要添加此代码以帮助服务器确定已发送数据的类型:

[request addValue:@"application/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];

如果您想为请求设置一些额外的标记,可以使用方法- (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field

答案 1 :(得分:0)

您所做的是完美的,请通过发送相同的请求来检查服务器端是否有正确的响应。