3

我有一个简单的 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);

}
4

2 回答 2

1

你在这里做什么:

[[NSURLConnection alloc] initWithRequest:request delegate:self];

此行返回一个 NSURLConnection 但您没有存储它。这对你无济于事。

在读取数据之前,您正在清除数据:

-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    response = [[NSMutableData data] retain]; // This line is clearing your data get rid of it
    NSString *responseString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
    NSLog(@"%@",responseString);

}

编辑

-(IBAction)buttonClick:(id)sender {

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://192.168.1.23/testService/JsonWS.asmx?op=FirmaGetir"]
                                                           cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
                                                       timeoutInterval:15];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:[@"firID=800" dataUsingEncoding:NSUTF8StringEncoding]];
    self.connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    [self.connection start];

}


#pragma NSURLConnection Delegates

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

    if (!self.receivedData){
        self.receivedData = [NSMutableData data];
    }
    [self.receivedData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

     NSString *responseString = [[NSString alloc] initWithData:self.receivedData encoding:NSUTF8StringEncoding];
     NSLog(@"%@",responseString);
}
于 2013-02-13T17:00:26.047 回答
0

我今天早上遇到了这个问题,我现在才弄清楚。我想您问题的关键是如何使用带有参数的 POST 方法。实际上,这很简单。

(1) 首先,您应该确保您的文件已准备好发送。这里我们说它是一个名为stringReady的 NSString 。我们在我们的postRequest方法中使用它作为参数(这里不是我们要讲的HTTP POST参数,别担心)。

// Send JSON to server
- (void) postRequest:(NSString *)stringReady{
// Create a new NSMutableURLRequest
NSMutableURLRequest *req = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://www.xxxxxx.io/addcpd.php"]];
[req setHTTPMethod:@"POST"];

(2) 现在,我们说服务器要获取的参数称为“数据”,这就是如何将参数插入 HTTP 正文的方式。

// Add the [data] parameter
NSString *bodyWithPara = [NSString stringWithFormat:@"data=%@",stringReady];

看,这是您在使用 POST 方法时添加参数的方式。您只需将参数放在要发送的文件之前。如果你知道你的参数是什么,那么你最好查看这个网站:

https://www.hurl.it/

这将帮助您测试您是否正确发送文件,并将在网站底部显示响应。

(3) 第三步,我们将我们的 NSString 打包成 NSData 并发送给服务器。

// Convert the String to NSData
NSData *postData = [bodyWithPara dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
// Set the content length and http body
NSString *postLength = [NSString stringWithFormat:@"%lu",(unsigned long)[postData length]];
[req addValue:postLength forHTTPHeaderField:@"Content-Length"];
[req setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[req setHTTPBody:postData];
// Create an NSURLSession
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:req
                                        completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                            // Do something with response data here - convert to JSON, check if error exists, etc....
                                            if (!data) {
                                                NSLog(@"No data returned from the sever, error occured: %@", error);
                                                return;
                                            }

                                            NSLog(@"got the NSData fine. here it is...\n%@\n", data);
                                            NSLog(@"next step, deserialising");

                                            NSError *deserr;
                                            NSDictionary *responseDict = [NSJSONSerialization
                                                                          JSONObjectWithData:data
                                                                          options:kNilOptions
                                                                          error:&deserr];
                                            NSLog(@"so, here's the responseDict\n\n\n%@\n\n\n", responseDict);
                                        }];

[task resume];}

希望这可以帮助被困在这里的人。

于 2017-08-03T03:02:50.700 回答