Http request with parameters

I have a simple asp.net webservice that returns json formatted data. I want to send an HTTP request with a parameter to get json data. How to send a request and receive data?

post request:

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>

      

I am trying to use some codes but they are not working.

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);

}

      

+3


source to share


2 answers


What do you do:

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

      

This line returns NSURLConnection, but you don't save it. It doesn't do anything for you.

You clear your data before reading:



-(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);

}

      

Edit

-(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);
}

      

+1


source


I experienced this problem this morning and now I figured it out. I think the key to your question is How to use POST method with parameter . It's actually quite simple.

(1) You must first make sure your file is ready to be sent. Here we say it is an NSString called stringReady. We use it as a parameter in our method called postRequest (not the HTTP POST parameter we want to talk about here. Don't worry).

// 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) Now we say that the parameter that the server wants to receive is called "data", so how to insert your parameter into the HTTP body.

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

      

See how you add the parameter when using the POST method. You just just put a parameter in front of the file you want to send. If you are aleary konw what your parameter is, then you might better check this site:



https://www.hurl.it/

This will help you check if the files were sent correctly and will display the response at the bottom of the website.

(3) Third, we pack our NSString into NSData and send it to the server.

// 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 the responseDict\n\n\n%@\n\n\n", responseDict);
                                        }];

[task resume];}

      

Hope this helps someone stuck here.

0


source







All Articles