Reqests Content-Type
should be set to application/x-www-form-urlencoded
NSMutableURLRequest returning null with POST
-
12-12-2021 - |
Frage
As per the title, I believe NSMutableURLRequest
is returning null
when I add in POST request? My server side is all set up and I am able to curl -F "test=test" 127.0.0.1
with my desired result.
As you can see from the methods below I have placed a few NSLog
s for error testing. The didReceiveResponse
and connectionDidFinishLoading
methods worked however didReceiveData
failed to call. Similar as to if I didn't place a POST message when I used curl and results in nothing. From this it leads me to think that I have missed something in the viewDidLoad
method.
I have also added how I send the response from the server using json encoding at the very bottom.
So have I missed something?
- (void)viewDidLoad {
NSString *yourPostString = [NSString stringWithFormat:@"test=test"];
dataWebService = [NSMutableData data];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://127.0.0.1/"]];
NSString *postLength = [NSString stringWithFormat:@"%d", [yourPostString length]];
[request addValue:@"text/html; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[request addValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:[yourPostString dataUsingEncoding:NSUTF8StringEncoding]];
myConnection = [NSURLConnection connectionWithRequest:request delegate:self];
[myConnection start];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[dataWebService setLength:0];
NSLog(@"Received Response");
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[dataWebService appendData:data];
NSLog(@"working %@", data);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *responseString = [[NSString alloc] initWithData:dataWebService encoding:NSUTF8StringEncoding];
NSLog(@"Response: %@",responseString);
}
Here is the send response function.
function sendResponse($status = 200, $body = '', $content_type = 'text/html'){
$status_header = 'HTTP/1.1 ' . $status . ' ' . getStatusCodeMessage($status);
header($status_header);
header('Content-type: ' . $content_type);
echo $body;
}
Lösung
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow