Comments (16)
I do. The request serializer already supports sending headers, check out: https://github.com/daltoniam/SwiftHTTP/blob/master/HTTPRequestSerializer.swift#L22
I am still weighing on how I want to return the headers in the response, hope to have that done soon.
from swifthttp.
+1 for the header.
from swifthttp.
Hot off the press. Just checked in a new way to interaction with the response. Now instead of just getting back a responseObject of the type AnyObject
you will get back a new HTTPResponse
object that contains a couple of variables. The responseObject will be in there as well as the headers. Let me know what you guys think.
from swifthttp.
nice @daltoniam , gotta check it out
from swifthttp.
@daltoniam Looks good. Thanks!
from swifthttp.
@daltoniam (or anyone else) can you provide an example that uses request headers?
I'm trying to do a GET request with Authorization headers for JSON Web Token, but I keep getting NSURLErrorDomain -1002 errors with the code below.
var request = HTTPTask()
request.requestSerializer = HTTPRequestSerializer()
request.requestSerializer.headers = ["Authorization": "Bearer " + self.jwt] // self.jwt is a string
request.responseSerializer = JSONResponseSerializer()
request.GET("http://myapi.com/resource", parameters: nil, success: {(response: HTTPResponse) -> Void in
if (response.responseObject != nil) {
success()
}
},
failure: {(error: NSError) -> Void in
// This fires.
failure()
})
I tried stepping through the debugger and https://github.com/daltoniam/SwiftHTTP/blob/master/HTTPRequestSerializer.swift#L97 looks suspicious, but I'm not exactly sure. Why does it assume GET requests have parameters?
from swifthttp.
@crzrcn I update the README with this example, but this should demonstrate how to send headers.
Web server in golang.
package main
import (
"fmt"
"log"
"net/http"
)
func main() {
http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) {
log.Println("got a web request")
fmt.Println("header: ", r.Header.Get("someKey"))
w.Write([]byte("{\"status\": \"ok\"}"))
})
log.Fatal(http.ListenAndServe(":8080", nil))
}
Now for the request:
var request = HTTPTask()
request.requestSerializer = HTTPRequestSerializer()
request.requestSerializer.headers["someKey"] = "SomeValue"
request.responseSerializer = JSONResponseSerializer()
request.GET("http://localhost:8080/bar", parameters: nil, success: {(response: HTTPResponse) -> Void in
if (response.responseObject != nil) {
println("got response: \(response.responseObject!)")
}
}, failure: {(error: NSError) -> Void in
println("got an error: \(error)")
})
from swifthttp.
I reproduced your example on my machine and I get the same error. Maybe it's something weird on my Xcode/machine? Ugh.
@daltoniam Thanks for responding though.
from swifthttp.
Yeah that is strange. I looked up -1002 error code and it is NSURLErrorUnsupportedURL
. Can you hit that same url in your browser and it responds properly? Error code sheet for reference:
from swifthttp.
Yup. Browser works fine. Tried "http://localhost:8080/bar" and "http://127.0.0.1:8080/bar", but neither work on the simulator.
The other HTTP request I have in my original code does work with SwiftHTTP. It's a POST though.
from swifthttp.
Interesting. I checked in some fixes a few hours ago for optional fixes that would be used by a GET request. Did you already pull that code?
from swifthttp.
Oh, now it's working. Hurray! Thanks.
from swifthttp.
Glad to hear it. Got to love the bleeding edge of new software 😄.
from swifthttp.
Sorry to comment on a closed issue, but response.headers doesn't work for me
(lldb) frame variable -L response.headers
0x7aee0ccc: ([String : String]?) response.headers = Some
(lldb) frame variable -L response.headers["Content-Type"]
error: unable to find any variable expression path that matches 'response.headers[Content-Type]'
from swifthttp.
hmmm, not sure why, is the request completing successfully? This example prints out the whole request, including the headers.
let task = HTTPTask()
task.GET("http://vluxe.io", parameters: nil, completionHandler: { (response: HTTPResponse) in
println("response is \(response.description)")
})
The debugger in Swift isn't always great at inspecting variable so you might want to try this as well:
if let heads = self.headers {
for (key, value) in heads {
println("\(key): \(value)\n")
}
} else {
println("no headers found")
}
from swifthttp.
This seems to have been lost when you refactored the API. I don't see this in HTTPSerializeProtocol or JSONParameterSerializer.
I did a quick review of the code and I did not see any way with the new API to set the Authorization header. I am also looking to use AWT for my app that is using SwiftHTTP.
from swifthttp.
Related Issues (20)
- Count is unavailable: there is no universally good answer, see the documentation comment for discussion HOT 5
- HTTP.POST() not working after screen-lock (iOS 9.3.5)
- How to handler download progress?
- 'count' is unavailable: there is no universally good answer, see the documentation comment for discussion
- failed in xcode9.3
- Pinning Trusted certs or keys HOT 2
- POST method parameters lost in traffic
- Parameters not converted properly when using arrays HOT 2
- Cannot upload file
- Progress closure seems broken
- Post objects array to server
- Ambiguous use of 'init(urlString:parameters:headers:cachePolicy:timeoutInterval:)'
- Retry a task?
- Why OperationQueue support has been removed?
- SSL Pinning - Code=-999 "cancelled" HOT 1
- Linux support ?
- Timeout
- 'taskMap' Dictionary related crashes in Operation.swift file HOT 3
- Cannot consume as Swift package
- SSL Pinning - Always failing
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from swifthttp.