I have implemented this code for "PUT" request:
var request: NSMutableURLRequest
let url:URL = URL(string: NetworkCallSDK.sharedSingleton().urlString! as String)!
request = NSMutableURLRequest(url: (url as URL) as URL)
print("getRequestHeaderWithAllParams:\(url)")
let parameter = ["key":"STRING"] as NSDictionary
let body = NSMutableData()
let boundary = "Boundary-\(UUID().uuidString)"
//define the multipart request type
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
for (key, value) in parameter
{
body.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!)
body.append("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n".data(using: String.Encoding.utf8)!)
body.append("\(value)\r\n".data(using: String.Encoding.utf8)!)
}
body.append("--\(boundary)--\r\n".data(using: String.Encoding.utf8)!)
request.httpMethod = "PUT"
request.httpBody = body as Data
request.timeoutInterval = 120
return request
And I am getting 500 status from server. And same API is working in Android. But same code for POST method is working fine for me.
The server is failing with an internal server error, which usually indicates either a crash or incorrectly formatted POST data. You have two problems here:
You're missing the Content-Type field for each of the request parts, which is required. You should probably add something like:
Content-Type: application/octet-stream
That's probably the cause of the 500 error.
Your data blob is almost certainly going to show up (NULL) or an empty string unless you're pre-encoding it with base64 (or similar) outside this code.
and then send the raw data. Otherwise, your server won't get the data. To do this, you need to do the following:
dataUsingEncoding:
method. If your server requires the data to be base64-encoded, convert the NSData to a string by calling base64EncodedDataWithOptions:
first. Either way, you should still be constructing the body as an NSData object.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.