I have been trying to connect my ios application to my restful web API through http basic authentication but I am unable to connect. Here is my code:
let URL = NSURL(string:"https://devWebsvc1.whateverYolo.local:11201/api/webcall")
let theRequest = NSMutableURLRequest(URL:URL)
let session = NSURLSession(configuration: NSURLSessionConfiguration.ephemeralSessionConfiguration())
theRequest.HTTPMethod = "POST"
theRequest.addValue("application/json", forHTTPHeaderField:"Content-Type")
theRequest.addValue("application/json", forHTTPHeaderField:"Accept")
let credential = NSURLCredential(user:"username", password:"password", persistence: NSURLCredentialPersistence.ForSession)
let protectionSpace = NSURLProtectionSpace(Host: URL?.host)!, port:11201, 'protocol': URL?.scheme, realm: nil, authenticationMethod: NSURLAuthenticationMethodHTTPBasic)
let credentialStorage = NSURLCredentialStorage.sharedCredentialStorage()
credentialStorage.setDefaultCredential(credential,forProtectionSpace:protectionSpace)
theSession.configuration.URLCredentialsStorage = credentialStorage
let task = theSession.dataTaskWithRequest(theRequest, completionHandler : {data, response, error -> Void in
if error != nil
{print("\(error)")}})
Error message is :-
Optional(Error Domain=NSURLErrorDomain Code=-1200 "An SSL error has occurred and a secure connection to the server cannot be made." UserInfo={NSURLErrorFailingURLPeerTrustErrorKey=, NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9802, NSErrorPeerCertificateChainKey={type = immutable, count = 1, values = (
0 :
)}, NSUnderlyingError=0x7fe023520170 {Error Domain=kCFErrorDomainCFNetwork Code=-1200 "(null)" UserInfo={_kCFStreamPropertySSLClientCertificateState=0, kCFStreamPropertySSLPeerTrust=, _kCFNetworkCFStreamSSLErrorOriginalValue=-9802, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9802, kCFStreamPropertySSLPeerCertificates={type = immutable, count = 1, values = (
0 :
)}}}, NSLocalizedDescription=An SSL error has occurred and a secure connection to the server cannot be made., NSErrorFailingURLKey=https://devwebsvc1.whateverYolo.local:11201/api/Device, NSErrorFailingURLStringKey=https://devwebsvc1.whateverYolo.local:11201/api/Device, NSErrorClientCertificateStateKey=0})
Do you guys know what could be the error? Any help is appreciated. I am using xcode 7 by the way.
Error may be in this line :-
theRequest.addValue("application/json", forHTTPHeaderField:"Accept")
You should go to this google extension and find what's the value for the Field "Accept"
chrome-extension://hgmloofddffdnphfgcellkdfbfbjeloo/RestClient.html
add Your url ,username and password and click submit and find all of your Header Field are correct like this, Check the value for Content-Type also
Related
I am attempting to create my first PowerBI Custom Connecter to connect to the Vimeo API. I am stuck on the final step of the authorization flow - getting back an access token. When trying out the Connecter in PowerBI, it seems to authenticate properly when I hit the access token endpoint, but I get back a warning "[unsupported_grant_type] Unsupported grant type"
It appears I am not sending the grant_type properly in the request. Here are Vimeo's requirements of what is sent along in the header and body of the request:
Header
Set value to
Authorization
basic base64_encode(x:y), where x is the client identifier and y is the client secret
Content-Type
application/json
Accept
application/vnd.vimeo.*+json;version=3.4
"In the request body, send the grant_type field with the value authorization_code. You must also set code to the authorization code string that you just received and redirect_uri to the redirect URI that you specified previously — don't use a different redirect URI."
{
"grant_type": "authorization_code",
"code": "{code}",
"redirect_uri": "{redirect_uri}"
}
Here is a snippet of code from the Customer Connector I am building. It is within this TokenMethod function that I am trying to fulfill the requirements of the table above. I am getting the sense I am not correctly placing the JSON in the body of the request, but I am stuck on what to try next:
TokenMethod = (grantType, tokenField, code) =>
let
queryString = [
grant_type = "authorization_code",
redirect_uri = redirect_uri,
client_id = client_id,
client_secret = client_secret
],
queryWithCode = Record.AddField(queryString, tokenField, code),
authKey = "Basic " & Binary.ToText(Text.ToBinary("client_id:client_secret"),BinaryEncoding.Base64),
tokenResponse = Web.Contents(token_uri, [
Content = Text.ToBinary(Uri.BuildQueryString(queryWithCode)),
Headers = [
#"Authorization" = authKey,
#"Content-type" = "application/json",
#"Accept" = "application/vnd.vimeo.*+json;version=3.4"
],
ManualStatusHandling = {400}
]),
body = Json.Document(tokenResponse),
result = if (Record.HasFields(body, {"error", "error_description"})) then
error Error.Record(body[error], body[error_description], body)
else
body
in
result;
I'm wondering if someone could please point out where I might be going astray in the code and why I am receiving the [unsupported_grant_type] error.
Many thanks for your time!
I changed Content-Type to "application/x-www-form-urlencoded" and it worked!
My goal is to post data to a Flask server. For this I have the following code running on a computer(Jupyter):
from flask import Flask
from flask import request
app = Flask(__name__)
#app.route('/postjson', methods = ['POST'])
def postJsonHandler():
print (request.is_json)
content = request.get_json()
print (content)
return 'JSON posted'
app.run(host='0.0.0.0', port= 8090)
On the esp I have the following function responsible for posting, Right now it is just for testing , I will further the functionality later on.
//Posts data to server
void post_to_server(String url)
{
HTTPClient http;
// Prepare JSON document
JsonObject root = doc.to<JsonObject>();
JsonArray pressure = root.createNestedArray("pressure");
JsonArray time = root.createNestedArray("time");
pressure.add("Pressure");
time.add("Time");
// Serialize JSON document
String json;
serializeJson(root, json);
// Send request
http.begin(url);
http.addHeader("Content-Type", "application/json");
int httpResponseCode = http.POST(json); //Send the actual POST request
// Read response
Serial.print(http.getString());
if (httpResponseCode > 0)
{
String response = http.getString(); //Get the response to the request
Serial.println(httpResponseCode); //Print return code
Serial.println(response); //Print request answer
}
else
{
Serial.print("Error on sending POST: ");
Serial.println(httpResponseCode);
// Disconnect
http.end();
}
}
So here is the odd thing, when I call the function on a test server like this:
post_to_server("http://jsonplaceholder.typicode.com/posts");
It works and I get the following response on the Serial Monitor as expected:
{
"pressure": [
"Pressure"
],
"time": [
"Time"
],
"id": 101
But when I try to post to the Server running on my PC like this:
post_to_server("http://127.0.0.1:8090/postjson");
I get the following error:
0
[E][WiFiClient.cpp:258] connect(): socket error on fd 54, errno: 104, "Connection reset by peer"
Error on sending POST: -1
I cant really make sense of this so I came here. I would appriciate any help. I also get the following when I test on Postman:
post_to_server("http://127.0.0.1:8090/postjson");
This will never work on your ESP32.
127.0.0.1 is the "loopback address" - the same as the name localhost. It's shorthand meaning "this computer".
When you use this with a program you run on your Windows machine, the program will attempt to connect to the Windows machine.
When you use this with your ESP32, it means connection to the ESP32.
You need to use the IP address associated with your Windows machine's network connection, whether ethernet or WiFi. 127.0.0.1 will not work.
I am trying access one of the Jenkins job's log using groovy script. but getting 403 error. How do I pass the credential to login in below code?
def jsonStr1 = new URL(myEnvUrl+"warnings40Result/api/json?pretty=true").getText()
You are getting HTTP 403 which stands for Unauthorized attempt.
Possibly there is a login page of Jenkins, you should include it to access your next page. page. Have a check following link:
Groovy built-in REST/HTTP client?
def jsonStr1 = new URL(myEnvUrl+"warnings40Result/api/json?pretty=true").getText()
I tried all the solution of url:
https://stackoverflow.com/questions/25692515/groovy-built-in-rest-http-client
i think without Login Credentials code we can't access 'jsonStr1'. so i tried below code, now i am able to access but while parsing the value its giving error:
code:200
[PostBuildScript] - Problem occurred: org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Content is not allowed in prolog.
my code:
def warningJsonUrl = EnvBuildUrl+"warnings40Result/api/json?token=4eca462899e426937a94006a20561011"
def authString = "admin1:admin1".getBytes().encodeBase64().toString()
def conn = warningJsonUrl.toURL().openConnection()
conn.setRequestProperty( "Authorization", "Basic ${authString}" )
if( conn.responseCode == 200 ) {
println("code:"+conn.responseCode)
def textJsonObj = new JsonSlurper().parseText(conn.content.text)
}
how i will parse as text?
I am retrieving data from URL like this:
let url = NSURL(string: baseURL)
let request = NSURLRequest(URL: url!)
let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
let task = session.dataTaskWithRequest(request) { (data, response, error) -> Void in
if error == nil {
let swiftyJSON = JSON(data: data!)
let results = swiftyJSON[0]["name"]
print(results)
} else {
print("error")
}
}
For the above, I get data like this:
[
{
"_id":"123",
"_rev":"345",
"name":"hey"
},
{
"_id":"133",
"_rev":"33345",
"name":"hello"
}
]
I always end up in error block and I am not sure why?
I pasted the JSON in chrome console and able to do swiftyJSON[0].name. I would like to print all elements from the above json OBJECT.
Error:
error Optional(Error Domain=NSURLErrorDomain Code=-1003 "A server with the specified hostname could not be found." UserInfo={NSUnderlyingError=0x7f87514ab570 {Error Domain=kCFErrorDomainCFNetwork Code=-1003 "(null)" UserInfo={_kCFStreamErrorCodeKey=8, _kCFStreamErrorDomainKey=12}}, NSErrorFailingURLStringKey=http://localhost:3000/idea, NSErrorFailingURLKey=http://localhost:3000/idea, _kCFStreamErrorDomainKey=12, _kCFStreamErrorCodeKey=8, NSLocalizedDescription=A server with the specified hostname could not be found.})
Please note, localhost:3000 is on.
The error you pasted may be the request's hostname not found.
"A server with the specified hostname could not be found." The JSON parse seems right totally.
The error is not in the JSON data. The data cannot be retrieved in the first place since the URL http://localhost:3000/idea is not working.
Most likey, the URL is valid on your Mac but not on your iPhone. The URL would only be valid if your server side was running on the iPhone or simulator itself, which is rather unlikely.
localhost isn't a global address. On your Mac, it refers to your Mac. On an iPhone, it refers to the iPhone itself.
Open the Network Utility app on your Mac, look up the IP address and replace localhost with your IP address, e.g. http://192.168.1.37:3000/idea. Then your iOS app will be able to retrieve the data.
This is my Json request
var postsEndpoint = "http://test/Search"
let test = ["SearchCriteria":["ForeName":"jack", "Surname":"jill"]];
request(.POST, postsEndpoint, parameters: test, encoding: .JSON)
.responseJSON { (request, response, data, error) in
if let anError = error
{
println("error calling POST on /posts")
println(error)
}
else if let data: AnyObject = data
{
let post = JSON(data)
println("The post is: " + post.description)
}
Is there an issue with my request as I am getting the following error:
error calling POST on /posts
Optional(Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Invalid value around character 3.) UserInfo=0x7fdd00414c80 {NSDebugDescription=Invalid value around character 3.})
Late, but I found this thread.
I ran into this same problem running a Django dev server and got You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data.
Append a slash to postsEndpoint so it becomes...
var postsEndpoint = "http://test/Search"