网络数据请求方式(SOAP和JSON)

从网络上进行数据的请求主要有SOAP方式和JSON方式,下面是我在看天气预报的例子时比较的两种方式的不同,在这里Mark一下。

SOAP方式:

使用SOAP获得天气预报支持的省直辖市信息

//封装soap请求消息

NSString*soapMessage = [NSStringstringWithFormat:

@"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"

"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"

"<soap:Body>\n"

"<getSupportProvince xmlns=\"http://WebXml.com.cn/\">\n"

"</getSupportProvince>\n"

"</soap:Body>\n"

"</soap:Envelope>\n",@"5"];

//请求发送到的路径

NSURL*url = [NSURLURLWithString:@"http://www.webxml.com.cn/WebServices/WeatherWebService.asmx"];

NSMutableURLRequest*theRequest = [NSMutableURLRequestrequestWithURL:url];

NSString*msgLength = [NSStringstringWithFormat:@"%d", [soapMessagelength]];

//以下对请求信息添加属性前四句是必有的,第五句是soap信息。

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

[theRequest addValue:@"http://WebXml.com.cn/getSupportProvince"forHTTPHeaderField:@"SOAPAction"];

[theRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"];

[theRequest setHTTPMethod:@"POST"];

[theRequest setHTTPBody: [soapMessagedataUsingEncoding:NSUTF8StringEncoding]];

//请求

NSURLConnection*theConnection = [[NSURLConnectionalloc]initWithRequest:theRequestdelegate:self];

//如果连接已经建好,则初始化data

if( theConnection )

{

webData= [[NSMutableDatadata]retain];

}


JSON方式:

使用iOS自带解析类NSJSONSerialization方法解析(ios5以上版本支持)

//取得苏州的天气情况

NSError *error;

   //加载一个NSURL对象

   NSURLRequest*request = [NSURLRequestrequestWithURL:[NSURLURLWithString:@"http://m.weather.com.cn/data/101190401.html"]];

   //将请求的数据放置到NSData中

   NSData*reponse = [NSURLConnectionsendSynchronousRequest:requestreturningResponse:nilerror:nil];

   //利用ios5自带的解析类NSJSONSerialization从response中解析出的数据放到字典中

   NSDictionary*weatherDic = [NSJSONSerializationJSONObjectWithData:reponseoptions:NSJSONReadingMutableLeaveserror:&error];

    NSDictionary *weather = [weatherDic objectForKey:@"weatherinfo"];

    weatherStr = [NSString stringWithFormat:@"今天是%@,%@,%@\n天气状况是,%@,%@",[weather objectForKey:@"date_y"],[weather objectForKey:@"week"],[weather objectForKey:@"city"],[weather objectForKey:@"weather1"],[weather objectForKey:@"temp1"]];

   NSLog(@"weather字典里的内容是:%@",weatherDic);