i got code error **status code: 400*
URL: https://conversation.8villages.com/1.0/contents/articles?state=published }
{ status code: 400, headers {
Connection = "keep-alive";
"Content-Length" = 2;
"Content-Type" = "application/json";
Date = "Tue, 11 Apr 2017 07:49:13 GMT";
Server = nginx;
} }
2 bytes
SUCCESS
JSON: {
}
my json is result SUCCESS but wht not show my DATA?
actually i get request method Alamofire with Consumer Key, Consumer Secret, Token Key and Token Secret. like this :
let params: HTTPHeaders = ["oauth_consumer_key":"*****",
"oauth_consumer_secret":"*****",
"oauth_token_key":"*****.",
"oauth_token_secret": "*****",
"oauth_signature_method": "HMAC-SHA1",
"oauth_timestamp_key" : "1491366048",
"oauth_version": "1.0"] as [String : Any] as! HTTPHeaders;
Alamofire.request("https://conversation.8villages.com/1.0/contents/articles?state=published", method: .get, headers: params).responseJSON { response in
print("test", response.request!) // original URL request
print("ini responseny", response.response!) // HTTP URL response
print("test", response.data!) // server data
print("test", response.result) // result of response serialization
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}
how to get my data API ??
Please keep in mind :
400 Bad Request : The server cannot or will not process the request
due to something that is perceived to be a client error (e.g.,
malformed request syntax, invalid request message framing, or
deceptive request routing).
For a better understanding check : this
Related
I want to get X-Dem-Auth in a header request with swift to stock that in my app.
See the response :
headers {
"Content-Length" = 95;
"Content-Type" = "application/json; charset=utf-8";
Date = "Fri, 15 Apr 2016 08:01:58 GMT";
Server = "Apache/2.4.18 (Unix)";
"X-Dem-Auth" = null;
"X-Powered-By" = Express;
If the response is type of NSHTTPURLResponse you can get header from response.allHeaderFields
As apple documentation says :
A dictionary containing all the HTTP header fields received as part of the server’s response. By examining this dictionary clients can see the “raw” header information returned by the HTTP server.
The keys in this dictionary are the header field names, as received from the server. See RFC 2616 for a list of commonly used HTTP header fields.
So to get for example a X-Dem-Auth in response header you can access it in that way :
if let httpResponse = response as? NSHTTPURLResponse {
if let xDemAuth = httpResponse.allHeaderFields["X-Dem-Auth"] as? String {
// use X-Dem-Auth here
}
}
UPDATE
Updated due to comment from Evan R
if let httpResponse = response as? HTTPURLResponse {
if let xDemAuth = httpResponse.allHeaderFields["X-Dem-Auth"] as? String {
// use X-Dem-Auth here
}
}
Update for iOS 13 and above.
I suggest if the response is of type HTTPURLResponse and you want get to a specific header value only. Then below is a better approach.
if let httpResponse = response as? HTTPURLResponse {
if let xDemAuth = httpResponse.value(forHTTPHeaderField: "X-Dem-Auth") as? String {
// use X-Dem-Auth here
}
}
I want to send POST request with JSON, I'm expecting JSON object with auth_token and refresh_token in response. My code looks like this:
let headers: HTTPHeaders = [
"Authorization": "Basic " + data.toBase64() //data is just string needed for authentication
]
// this should be a JSON
let parameters = [
"code": self.code,
"grant_type": "authorization_code",
"redirect_uri": "populi://callback"
]
Alamofire.request("https://populi.pl/api/v1/auth/token", method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseString { response in
print(response.request)
print("\n3 RESPONSE : \(response)")
print("\n3 POST : \(response.response)")
print("\n3 DATA : \(response.data)")
print("\n3 RESPONSE RESULT : \(response.result)")
print("\n3 RESPONSE RESULT VALUE : \(response.result.value)")
print("3 ERROR : \(response.error)")
}
Yeah, I print a lot of things, that's because I'm new to networking.
In response I'm getting 301 moved permanently. Why? I have no idea what's wrong. Is this wrong JSON in parameters or maybe something with redirecting? I should get 200 and JSON in response.
try this
func getData(){
let todoEndpoint: String = Your url
let params: Parameters = [yor parameters]
let headers: [String : String] = [
"Content-Type": "application/x-www-form-urlencoded",
]
Alamofire.request(todoEndpoint, method: .post, parameters: params,headers: headers)
.responseJSON { response in
switch response.result {
case .success:
let json = JSON(response.result.value as Any)
print(json)
break
case .failure(let error):
print(error)
}
}
}
I solved this with "/" at the end of request URL.
I was using URLSession for requests and was getting 301 for 1 request
then I tried Alamofire and still got the same response and at the end, I figured out that issue was that I was not appending / at the end of endpoint
I'm new to Alamofire, have been trying to work with a web service that I can use through Postman but I can't use via Alamofire. In Postman I can set HTTP Header Key "Accept" with "application/json" and I get a response in Content-Type →application/json; charset=utf-8.
However when I try to do the same using Alamofire, the serialization fails cause the response comes in xml.
Is there a solution for this? I tried custom HTTP Headers & defaulting session manager with the "Accept" key being set to "application/json" but I can't get the intended response! Here is a sample of the code.
if let url = URL(string: "http://madinaty.demoday.us/api/1/lookup/stable/") {
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = HTTPMethod.get.rawValue
urlRequest.addValue("application/json", forHTTPHeaderField: "content-type")
urlRequest.addValue("application/json", forHTTPHeaderField: "accept")
let request = Alamofire.request(urlRequest)
.responseJSON{ response in
print("Request: \(String(describing: response.request))") // original URL request
print("---------------------------")
print("HTTP URL response: \(String(describing: response.response))") // HTTP URL response
print("---------------------------")
print("Data: \(String(describing: response.data))") // server data
print("---------------------------")
print("Result of Reponse Serialization \(response.result)") // result of response serialization
print("---------------------------")
print("Error \(response.result.error)") // result of response serialization
print("---------------------------")
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}
This is the error I get:
Optional(Alamofire.AFError.responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error
Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character
0." UserInfo={NSDebugDescription=Invalid value around character 0.})))
I also tried this:
let header = ["content-type" : "application/json"]
Alamofire.request("http://madinaty.demoday.us/api/1/lookup/stable/",
method: .get,
parameters: nil,
encoding: JSONEncoding.default,
headers: header).responseJSON {
response in
print(response.request) // original URL request
print(response.response) // HTTP URL response
print(response.data) // server data
print(response.result) // result of response
}
Doesn't work either!
Neither did this work:
// get the default headers
var headers = Alamofire.SessionManager.defaultHTTPHeaders
// add your custom header
headers["Accept"] = "application/json"
// create a custom session configuration
let configuration = URLSessionConfiguration.default
// add the headers
configuration.httpAdditionalHeaders = headers
// create a session manager with the configuration
let sessionManager = Alamofire.SessionManager(configuration: configuration)
// make calls with the session manager
let request = sessionManager.request("http://madinaty.demoday.us/api/1/lookup/stable/")
.responseJSON { response in
debugPrint(response)
print("Result of Reponse Serialization \(response.result)")
}
debugPrint(request)
After hours of different trials, I finally found the solution for the problem
It turned out that just removing the trailing slash of the URL would solve the problem!
Try creating a custom session header configuration:
var headers = Alamofire.SessionManager.defaultHTTPHeaders
headers["content-type"] = "application/json"
// custom session configuration
let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = headers
let sessionManager = Alamofire.SessionManager(configuration: configuration)
Then make your request using sessionManager.request(...) instead of Alamofire.request(...)
I'm using Laravel 5.3 as an API for my iOS app. When I try to make HTTP calls with headers and parameters I get this 401 error:
message = "Could not decode token: The token
\"Optional(\""eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjUsImlzcyI6Imh0dHA6XC9cL2xvY2FsaG9zdDo4MDAwXC9hcGlcL2F1dGhcL3Bvc3RMb2dpbiIsImlhdCI6MTQ4MDUzNzQxOCwiZXhwIjoxNDgwNTQxMDE4LCJuYmYiOjE0ODA1Mzc0MTgsImp0aSI6ImMyZmYxNzI5N2U5OGU4MzkzYzZkZWRmNTZlN2ZkMzNkIn0.u6sQqlq5k-B5jhZ7EymkXLlcTIQ-i7X_83an5irwTss\"" is an
invalid JWS";
"status_code" = 401; }
This is the code that makes the HTTP request:
let headers = ["Authorization":"Bearer \(token)"]
request(url! , method: .get, parameters: nil, encoding: JSONEncoding.default , headers: headers )
.responseJSON { response in
print("RESPONSE \(response)")
I did some googling and found a package to encode JWT called JWTDecode.swift. Here is the link to the code: https://github.com/auth0/JWTDecode.swift. I still couldn't figure out how to solve this issue.
change
let headers = ["Authorization":"Bearer \(token)"]
to something like
guard let token = token else { return }
let headers = ["Authorization":"Bearer \(token)"]
otherwise you are sending Optional(<token>) instead of <token>.
I am using Alamofire for networking and SwiftyJSON for parsing server response in my iOS app.
I always get unknown while trying to do this println(JSON(data!))
Here is my request code :
Alamofire.request(.GET, URLString: "http://httpbin.org/get", parameters: ["foo": "bar"])
.response { (request, response, data, error) in
println("request ==== \(request)")
println("response ==== \(response)")
println("error ==== \(error)")
println("json ==== \(JSON(data!))")
println("data ==== \(data)")
}
And here is my console output :
request ==== <NSMutableURLRequest: 0x15e9a4e0> { URL: http://httpbin.org/get?foo=bar }
response ==== Optional(<NSHTTPURLResponse: 0x15ddc910> { URL: http://httpbin.org/get?foo=bar } { status code: 200, headers {
"Access-Control-Allow-Credentials" = true;
"Access-Control-Allow-Origin" = "*";
Connection = "keep-alive";
"Content-Length" = 430;
"Content-Type" = "application/json";
Date = "Wed, 04 Feb 2015 09:12:45 GMT";
Server = nginx;
} })
error ==== nil
json ==== unknown
data ==== Optional(<7b0a2020 22617267 73223a20 7b0a2020 20202266 6f6f223a 20226261 72220a20 207d2c20 0a202022 68656164 65727322 3a207b0a 20202020 22416363 65707422 3a20222a 2f2a222c 200a2020 20202241 63636570 742d456e 636f6469 6e67223a 2022677a 69703b71 3d312e30 2c636f6d 70726573 733b713d 302e3522 2c200a20 20202022 41636365 70742d4c 616e6775 61676522 3a202266 723b713d 312e302c 656e3b71 3d302e39 2c64653b 713d302e 382c7a68 2d48616e 733b713d 302e372c 7a682d48 616e743b 713d302e 362c6a61 3b713d30 2e35222c 200a2020 20202248 6f737422 3a202268 74747062 696e2e6f 7267222c 200a2020 20202255 7365722d 4167656e 74223a20 224f7545 73744d6f 6e43616d 696f6e2f 636f6d2e 50697865 6c734163 6164656d 792e4f75 4573744d 6f6e4361 6d696f6e 2028313b 204f5320 56657273 696f6e20 372e312e 32202842 75696c64 20313144 32353729 29220a20 207d2c20 0a202022 6f726967 696e223a 20223139 372e3134 2e31302e 3234222c 200a2020 2275726c 223a2022 68747470 3a2f2f68 74747062 696e2e6f 72672f67 65743f66 6f6f3d62 6172220a 7d0a>)
Am i doing something wrong?
The unknown value being printed is coming from SwiftyJSON. It appears that you are using the incorrect initializer. Instead you want to try the following.
var parsingError: NSError?
let json = JSON(data: dataFromServer, error: &error)
println(json)
println(parsingError)
This will run NSJSONSerialization.JSONObjectWithData over your NSData that you send into SwiftyJSON. If it succeeds, you'll get a valid JSON object. If it fails, you will still get your unknown type but the parsingError will tell you why parsing failed.
One last tip is that you could try to encode the dataFromServer to be able to visualize it properly. Here's how you could do that.
if let dataFromServer = dataFromServer as? NSData {
if let encodedData = NSString(data: dataFromServer, encoding: NSUTF8StringEncoding) {
println(encodedData)
}
}
Hope that helps!
I think that the problem was relative to the Alamofire library under iOS7. I ended up by working with AFNetworking and parsing web service response with SwiftyJSON without any strange problems.