我有一个简单的asp.net Web服务,它返回json格式的数据。我想发送带参数的http post请求来获取json数据。我该如何发送请求并获取数据?
post请求:
POST /JsonWS.asmx/FirmaGetir HTTP/1.1
Host: localhost
Content-Type: application/x-www-form-urlencoded
Content-Length: length
firID=string
answer:
HTTP/1.1 200 OK
Content-Type: text/xml; charset=utf-8
Content-Length: length
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">string</string>
我尝试了一些代码,但它们没有起作用。
NSString *firmadi =@"";
NSMutableData *response;
-(IBAction)buttonClick:(id)sender
{
NSString *firid = [NSString stringWithFormat:@"800"];
response = [[NSMutableData data] retain];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://192.168.1.23/testService/JsonWS.asmx?op=FirmaGetir"]];
NSString *params = [[NSString alloc] initWithFormat:@"firID=%@",firid];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if(theConnection)
{
response = [[NSMutableData data] retain];
}
else
{
NSLog(@"theConnection is null");
}
}
-(void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)responsed
{
[response setLength:0];
NSURLResponse * httpResponse;
httpResponse = (NSURLResponse *) responsed;
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data
{
[response appendData:data];
//NSLog(@"webdata: %@", data);
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError*)error
{
NSLog(@"error with the connection");
[connection release];
[response release];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
response = [[NSMutableData data] retain];
NSString *responseString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSLog(@"%@",responseString);
}