SoFunction
Updated on 2025-04-07

IOS problem with POST network request status code:500 solution

IOS problem with POST network request status code:500 solution

Preface:

iOS 10[NSURLSession uploadTaskWithRequest:request fromData:jsondata completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error){}];

500 error occurred while making a post network request

An error of 500 occurred The server encountered an unexpected situation, which caused it to fail to complete the processing of the request. Generally speaking, this problem will occur when the server's program code errors.Summary of common status codes for IOS HTTP requests

Although this reason is a server error, I think the server parsing the request data may also cause this error status of 500, so I started from the client service.
The value in the response when printing is returned is

:<NSHTTPURLResponse: 0x17003a900> { URL: yoururladdress } { status code: 500, 

headers {
 "Cache-Control" = private
 "Content-Length" = 3306;
 "Content-Type" = "text/html; charset=utf-8";
 Date = "Sun, 09 Oct 2016 07:45:13 GMT";
 Server = "Microsoft-IIS/7.5";
 "X-AspNet-Version" = "4.0.30319";
 "X-Powered-By" = "";
} }

From this we can see that the return type is not json but text/html type

We know that in the post request, you need to set the request header data type. This is how I set the above error request.

[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; 

This setting method is copied from the network request method for submitting the image, that is, @"application/x-www-form-urlencoded" is the type setting of the submitted image (when submitting the image parameters are converted to NSData and then converted to base64's NSData submission). And my request is the NSData type that submits the json string. So set the value of "Content-Type" to "application/json".Detailed explanation of Content-Type explanation in Http request and its application in Spring MVC

My solution is to reset it as follows:

[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; 

Request response You can compare with the above.

<NSHTTPURLResponse: 0x17403fe60> { URL: yoururladdress } { status code: 200, headers {
 "Cache-Control" = private;
 "Content-Length" = 75;
 "Content-Type" = "application/json; charset=utf-8";
 Date = "Sun, 09 Oct 2016 07:56:16 GMT";
 Server = "Microsoft-IIS/7.5";
 "X-AspNet-Version" = "4.0.30319";
 "X-AspNetMvc-Version" = "4.0";
 "X-Powered-By" = "";
} } 

The current status code: 200 solved the problem of 500 errors. This error may also cause errors in the background processing of data, or conflicts between the data type returned by the background and the type that needs to be returned by the front-end settings, etc. Need to analyze specific issues

Thank you for reading, I hope it can help you. Thank you for your support for this site!