我尝试连接到 Web 服务并从中检索数据,但没有成功。这是我所做的。
这是我试图连接到http://www.rcsb.org/pdb/software/rest.do的网络服务
这是我的 example.h 文件:
#import <Foundation/Foundation.h>
@interface example : NSObject {
NSMutableData *receivedData;
}
@property(nonatomic, retain) NSMutableData *receivedData;
- (void) getDataFromServer;
@end
这是我的 example.m 文件:
导入“example.h”
@implementation example
@synthesize receivedData;
-(void) getDataFromServer {
//prepare request
NSString *urlString = [NSString stringWithFormat:@"http://www.rcsb.org/pdb/rest/search/"];
NSMutableURLRequest *theRequest = [[NSMutableURLRequest alloc] init];
[theRequest setURL:[NSURL URLWithString:urlString]];
[theRequest setHTTPMethod:@"POST"];
NSString *myXmlQuery = [[NSString alloc] initWithFormat:@"<?xml version=\"1.0\" encoding=\"UTF-8\"?><orgPdbQuery><version>head</version><queryType>org.pdb.query.simple.AdvancedKeywordQuery</queryType><description>Text Search for: chloro</description><keywords>chloro</keywords></orgPdbQuery>"];
//set Headers
NSString *contentType = [NSString stringWithFormat:@"application/xml"];
[theRequest addValue:contentType forHTTPHeaderField:@"Content-Type"];
[theRequest addValue:[NSString stringWithFormat:@"%ld", [myXmlQuery length]] forHTTPHeaderField:@"Content-Length"];
//create the Body
NSMutableData *postBody = [NSMutableData data];
[postBody appendData:[[NSString stringWithFormat:@"<xml>"] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[myXmlQuery dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:@"</xml>"] dataUsingEncoding:NSUTF8StringEncoding]];
//post
[theRequest setHTTPBody:postBody];
NSLog(@"%@", myXmlQuery);
//get response
NSHTTPURLResponse *urlResponse = [[NSHTTPURLResponse alloc] init];
NSError *error = [[NSError alloc] init];
NSData *responseData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&urlResponse error:&error];
NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(@"Response code- %ld",[urlResponse statusCode]);
NSLog(@"Response: %@", result);
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(@"in didReceiveResponse....setting receivedData to zero");
//[receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSLog(@"In didReceiveData...receiving data and appending to receivedData");
[receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(@"Connection failed with error");
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(@"in connectionDidFinishLoading");
NSLog(@"Succeeded! Received %ld bytes of data", [receivedData length]);
}
@end
我得到一个 html 页面作为对此的回应。此外,connectionDidFinishLoading 任何时候都不会被调用,因为我的输出中没有得到 NSLog 语句。我得到的只是我试图连接的 url 的 html 版本。
任何形式的帮助将不胜感激。谢谢你。
PS:我正在尝试正确格式化此文本,但它会自动格式化为这样。带来不便敬请谅解。