我有一个简单的 asp.net Web 服务,它返回 json 格式的数据。我想发送带有参数的http post请求以获取json数据。如何发送请求并获取数据?
发帖请求:
POST /JsonWS.asmx/FirmaGetir HTTP/1.1
Host: localhost
Content-Type: application/x-www-form-urlencoded
Content-Length: length
firID=string
回答:
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);
}