chandra mohan
chandra mohan

Reputation: 337

Http post request works fine in postman but not in iOS?

I'm using RestKit to making network request. I'm using basic auth. I'm trying to make post call to server. It's giving me 401 error. But i took same request body and header tried same request in postman and It's working fine.

code in swift

  let requestMapping: RKObjectMapping = self.defineSyncUserProfileRequestMapping().inverseMapping()
        objectManager.addRequestDescriptor(RKRequestDescriptor(mapping: requestMapping, objectClass: UserProfile.self, rootKeyPath: nil, method: RKRequestMethod.POST))

        let responseMapping = self.defineSyncUserProfileResponseMapping() as RKDynamicMapping

        let responseDesriptor = RKResponseDescriptor(mapping: responseMapping, method: RKRequestMethod.POST, pathPattern: HabitsConstants.WebServicePath.POST_USER_PROFILE, keyPath: "", statusCodes: RKStatusCodeIndexSetForClass(UInt(RKStatusCodeClassSuccessful)))

        objectManager.addResponseDescriptor(responseDesriptor)

        objectManager.requestSerializationMIMEType = RKMIMETypeJSON
        self.objectManager.HTTPClient .setAuthorizationHeaderWithUsername(self.userCredential.username, password: self.userCredential.password)
        self.objectManager.HTTPClient.setDefaultHeader("Content-type" , value: RKMIMETypeJSON)
        RKMIMETypeSerialization.registerClass(RKNSJSONSerialization.self, forMIMEType: "text/json")


        objectManager.postObject(userProfile, path: URL, parameters: nil,
                                 success:{ operation, mappingResult in
                                    let response: NSArray = mappingResult.array()
                                    if response.count > 0 {
                                        if (response.objectAtIndex(0) .isKindOfClass(Error)) {
                                            let error: Error = response.objectAtIndex(0) as! Error
                                            NSLog("ERROR \(error.errorReason)");
                                            self.delegate?.handleMessage(MessageType.ERROR, data: 1.0,errorMessage: error.errorReason)
                                        } else if (response.objectAtIndex(0) .isKindOfClass(UserCredentialResponse)) {
                                            NSLog("Saved profile for user\(userProfile.userId)");
                                            self.getUserProfile()
                                            self.getUserTargets()
                                        }
                                    }

            },
                                 failure:{ operation, error in
                                    NSLog("Error: \(error!.localizedDescription)")
                                    self.delegate?.handleMessage(MessageType.UNKOWN_ERROR, data: 1.0,errorMessage: "")
            }
        )

post man code

POST /dmanager/v5/updateprofile/ HTTP/1.1
Host: host.com
Content-Type: application/json
Authorization: Basic aHNoc25hbmE4MjMxOmpzanNqc2pzampz
Cache-Control: no-cache
Postman-Token: 23a32222-db02-b8bb-63cb-da5faffc27be
{"age":23,"phone_number":"","user_id":19709,"weight":25,"key":"jsjsjsjsjjs","set_first_login":"true","first_name":"Suisse","height":91.44,"last_name":"","email":"[email protected]","gender":"M"}

Upvotes: 2

Views: 2760

Answers (1)

Grant Lindsey
Grant Lindsey

Reputation: 105

I had a similar issue. Request body from Swift was identical to the Postman request and I was getting Bad Request responses from the Django Rest Framework API host.

Postman adds the Content-Type header with value application/json if that's the body type you've indicated. I tried setting it myself from within my Swift iOS request client (see this answer FMI) and I'm now getting successful responses.

The relevant snippet I used:

var request = URLRequest(url:renderedUrl)
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept")

Upvotes: 1

Related Questions