I'm trying to connect my Java application to the Watson NLU service. For a start, I tried to follow the tutorial from Bluemix. I created a service on Bluemix and imported the watson Java SDK. Using this tutorial code, I keep receiving 401 - not authorized responses. (Of course i changed username and password for the service).
I guess there's something missing, but i can't figure out what.
NaturalLanguageUnderstanding service = new NaturalLanguageUnderstanding(
NaturalLanguageUnderstanding.VERSION_DATE_2017_02_27,
"{username}",
"{password}"
);
String text = "IBM is an American multinational technology " +
"company headquartered in Armonk, New York, " +
"United States, with operations in over 170 countries.";
EntitiesOptions entitiesOptions = new EntitiesOptions.Builder()
.emotion(true)
.sentiment(true)
.limit(2)
.build();
KeywordsOptions keywordsOptions = new KeywordsOptions.Builder()
.emotion(true)
.sentiment(true)
.limit(2)
.build();
Features features = new Features.Builder()
.entities(entitiesOptions)
.keywords(keywordsOptions)
.build();
AnalyzeOptions parameters = new AnalyzeOptions.Builder()
.text(text)
.features(features)
.build();
AnalysisResults response = service
.analyze(parameters)
.execute();
System.out.println(response);
i had the same problems in node.js and solved it by adding the correct url of the api gateway to the NaturalLanguageUnderstanding service = new NaturalLanguageUnderstanding() object.
please keep in mind, that this depends on your region ..
regards
Leo
A 401 Unauthorized would suggest that there's an issue with the credentials that you're using to access the service. To rule this out, take a start by using the cURL tutorial from that same page:
curl -X POST \
-H "Content-Type: application/json" \
-u "{username}":"{password}" \
-d #parameters.json "https://gateway.watsonplatform.net/natural-language-understanding/api/v1/analyze?version=2017-02-27"
If, with that same username and password, you still receive a 401 Unauthorized error, then there's likely an issue with that username/password combination. Delete the tile in Bluemix and create a new one to get a new username/password, and give that a try.
If that does work fine, then there's an issue with how the username/password is being inserted into the code. Verify that you've replaced {username} and {password}, the final version should not have any curly brackets in it.
Related
Trying to read data of specific envelopes from DocuSign using completely backend java process ... and after some trial and error I've obtained AccessToken with JWT grant but still getting authorization error when asking for actual data :(
Defined new integration key 9xxx7e
User Application: Authorization Code Grant
No secrets added
Service Integration - uploaded public RSA key
Added one Redirect URI (regardless I don't need any)
Manual confirmation of corresponding link : https://account-d.docusign.com/oauth/auth?response_type=code&scope=signature%20impersonation&client_id=9xxx7e&state=123&redirect_uri=https://my.redirect.net/DocuSign ... assuming it is just one-time action
Successfully requested Access Token using java code (using com.docusign:docusign-esign-java:3.10.1)
ApiClient = new ApiClient(ApiClient.DEMO_REST_BASEPATH);
OAuthToken token = apiClient.requestJWTApplicationToken(integrationKeyJwt, scopes, privateKeyFileContent, 3600);
Trying to get envelope data using simple HttpGet
HttpGet request = new HttpGet("https://demo.docusign.net/restapi/v2.1/accounts/6xxx1e/envelopes");
request.addHeader("Content-Type", "application/json");
request.addHeader("Authorization", "Bearer " + token.getAccessToken());
but still got 401 response with content:
{"errorCode":"AUTHORIZATION_INVALID_TOKEN","message":"The access token provided is expired, revoked or malformed. Authentication for System Application failed."}
Please any idea what is wrong? How to obtain correct Access Token?
P.S.: I also tried to get Authorization Code Grant without JWT or implicit grant but no luck without browser tough :(
I would recommend that you print the accessToken you're creating in a file and use in Postman. This will at least help you narrow it down to either the Token generation step or sending the request portion.
Let us know what you find.
Problem was/is with use of apiClient.requestJWTApplicationToken but apiClient.requestJWTUserToken is the way to go
I am trying to make an API call using Restlet in java however when I run my code I get an org.restlet.resource.ResourceException: Unauthorized (401) - The request requires user authentication
The format for the API call is as follows for shell: curl "<api_url>" \ -H "Authorization: Bearer <api_token_here>"
However I am unsure how to add this authorization header in Restlet, as you are not able to add the header using .getRequest().getHeaders().add();
Additionally I have tried to set a challenge response however this also does not appear to work.
API = new ClientResource(RequestURL);
API.setProtocol(Protocol.HTTPS);
ChallengeResponse AuthHeader = new ChallengeResponse(ChallengeScheme.CUSTOM);
AuthHeader.setRawValue("Authorization: Bearer " + APIKey);
API.getRequest().setChallengeResponse(AuthHeader);
API.get();
I appear to have solved the issue with the following code:
ChallengeResponse AuthHeader = new ChallengeResponse(ChallengeScheme.HTTP_OAUTH_BEARER);
AuthHeader.setRawValue(APIKey);
AuthHeader.setIdentifier("Bearer");
API.setChallengeResponse(AuthHeader);
I want to get access token OAuth 2.0 from REST API via Java code, the thing is that I've managed to successfully get it back from the server with Bash script (curl command)
Bash script (working):
#!/usr/bin/env bash
# Base URL of TeamForge site.
site_url="https://teamforge.example.com"
# TeamForge authentication credentials.
username="foo"
password="bar"
# Requested scope (all)
scope="urn:ctf:services:ctf
curl -d "grant_type=password&client_id=api-client&scope=$scope&username=$username&password=$password" $site_url/sf/auth/token
With that code snippet I'got this response:
{
"access_token": "eyJraWQiOiIxIiwiYWxnIjoiUlMyNTYifQ.eyJzdWIiOiJhZG1pbiIsImF1ZCI...",
"token_type": "Bearer"
}
When I've tried to translate it to Java code using Unirest :
HttpResponse<JsonNode> jsonResponse = Unirest.post("\"https://teamforge.example.com/sf/auth/token")
.header("accept", "application/json")
.body("{\"grant_type\":\"password\"," +
"\"client_id\":\"api-client\", " +
"\"scope\":\"urn:ctf:services:ctf\"," +
"\"username\":\"foo\"," +
"\"password\":\"bar\"}")
.asJson();
System.out.println(jsonResponse.getBody());
Response was:
{"error_description":"Invalid grant","error":"invalid_grant"}
After a couple of researches and tries, I still don't know what am I missing in my Java code request. Can someone help me to add missing stuff or guide me to right directions?
CollabNet docs:
Saso
Please try:
JsonNode jsonResponse = Unirest.post("https://teamforge.example.com/sf/auth/token")
.header("Content-Type", "application/json")
.field("scope", "urn:ctf:services:ctf")
.field("client_id", "api-client")
.field("grant_type", "password")
.field("username", "foo")
.field("password", "bar")
.asJson()
.getBody();
And one more question are you sure about grant type ?
grant_type = client_credentials maybe you need something like this.
Our infra team set up the ca service desk in machine and share the details. I need to make rest call to create the incident from java program. And here i want to use basic authentication by providing the access key. For this I tried to make the end point url to get the access key and after that to create incident as shown below.
http://Host:port/caisd-rest/rest_access
http://CAdeskHost:port/caisd-rest/in
String endpoint = "http://host:port/caisd-rest/rest_access";
HttpClient client = new HttpClient();
String encodedCredentials = new String(Base64.encodeBase64(("username" + ":" + "password").getBytes()));
PostMethod post = new PostMethod(endpoint);
post.addRequestHeader("Accept", "application/xml");
post.addRequestHeader("Content-Type", "application/xml; charset=UTF-8");
post.addRequestHeader("Authorization", "Basic " + encodedCredentials);
post.setRequestBody("<rest_access/>");
try {
System.out.println("Execute Basic Authentication request on " + endpoint);
// Execute request
int result = client.executeMethod(post);
But when I try to execute the above code, getting the 404 error
"The requested resource (/caisd-rest/rest_access) is not available".
Can any one please help me how to find the REST URL for ca service desk whether it is common url for all like /caisd-rest or it is different. Here my infra team just installed the CA service desk. So do we need to do any other steps to provide rest access?
Check in CA Technologies Website, it should be http://<host>:<REST port>/caisd-rest
I had the same issue, problem was that REST wasn't deployed properly, reconfiguring REST Service using this doc: REST API reconfiguration resolved the problem.
I folowed these steps:
Check for existence of NX_ROOT/bopcfg/www/CATALINA_BASE_REST/webapps/caisd-rest. If this directory does NOT exist, that's a very good indication that the REST deploy did not work properly.
Check for the errors in NX_ROOT/log/jrest.log file.
Try fix errors and redeploy REST Service using cmd:
pdm_rest_util -undeploy
pdm_rest_util -deploy
im using dropwizard. From a resource i try to use bitcoin rpc via Jersey HttpClient.
using curl works like a charm:
$ curl --user user:password -X POST -d '{"jsonrpc": "1.0", "id":"curltest", "method": "getinfo", "params":
[] }' -H 'content-type: text/plain;' http://domain.name:18332/
But somehow using Jersey HTTP client from a resource doesnt work:
//init in run methode
final Client client = new JerseyClientBuilder(e).using(c.getJerseyClientConfiguration()).build(getName());
HTTPBasicAuthFilter httpBasicAuth = new HTTPBasicAuthFilter("user", "password");
client.addFilter(httpBasicAuth);
//From the resource
WebResource webRes = client.resource("http://domain.name:18332/");
webRes.header("content-type", "text/plain");
RPC_REQUEST rpc = new RPC_REQUEST("1.0", "curltest", "getinfo", new ArrayList<String>());
String response = webRes.post(String.class, JSONParserHelper.parseJSONToString(rpc));
JSONParserHelper.parseJSONToString(rpc) returns following string:
{"jsonrpc":"1.0","id":"curltest","method":"getinfo","params":[]}
Following error is caused in row "webRes.post":
! com.sun.jersey.api.client.UniformInterfaceException: Client response status: 500
EDIT: Using a wrong pw causes a 401. I guess the connection should be correct and the issue is somewhere else.
EDIT: Used -d instead of --data-binary
EDIT: As soon as Im home Ill dump the whole request from jersey http client.
Thank you
Bitcoin RPC does not support chunked encoding requests.
Since there was a bug in dropbox jersey libs till 0.8 you cannot disable it.
Since 0.8 you can disable it in the configuration file.
I had to migrate from 0.7 to 0.8 and add this in my configuration file.
httpClient:
...
chunkedEncodingEnabled: false
By the way a good migration overview: https://groups.google.com/forum/#!topic/dropwizard-dev/VInOW_ebiAc