I'm attempting to authorize with the Lithium Social Web API in Java. I am relatively new to Java but it feels like what I have should work. I am using webTarget and Invocation builder to try and pass the authorization through the header but continually get an unauthorized response.
I've changed the authentication to Base64 encoded via the AuthenticationClass below and can authenticate through hurl.it with the API and can get data back so the user credentials are correct. I've attached a sample of the code with the username and password removed. If anyone has any ideas i would appreciate it.
this.webTarget = this.client.target("https://socialweb-analytics.lcloud.com");
WebTarget webTargetSessionAuthenticate = webTarget.path("/api/public/reports/report/conversation");
AuthenticationClass newAuth = new AuthenticationClass();
newAuth.loginValue("USERNAME", "PASSWORD");
loginValue = newAuth.encodeLogin();
Object [] starttimeParamObjects = {new String("1438351200000")};
Object [] reportformatParamObjects = {new String("csv")};
Object [] endtimeParamObjects = {new String("1439128800000")};
Object [] companykeyParamObjects = {new String("XXX")};
System.out.println(loginValue);
WebTarget webTargetSessionAuthenticateWithQueryParams = webTargetSessionAuthenticate
.queryParam("startTime", starttimeParamObjects)
.queryParam("endTime", endtimeParamObjects)
.queryParam("reportFormat", reportformatParamObjects)
.queryParam("companyKey", companykeyParamObjects);
System.out.println(webTargetSessionAuthenticateWithQueryParams);
Invocation.Builder invocationBuilderAuth =
webTargetSessionAuthenticateWithQueryParams.request();
invocationBuilderAuth.header(HttpHeaders.AUTHORIZATION, "Basic " + loginValue);
Response response = invocationBuilderAuth.get();//Entity.entity("", MediaType.TEXT_PLAIN_TYPE));
int responseStatus = response.getStatus();
System.out.println(responseStatus);
System.out.println(response.readEntity(String.class));
A space is required between your header string "Basic" and "encoded login Value value". So try to change this
invocationBuilderAuth.header(HttpHeaders.AUTHORIZATION, "Basic" + loginValue);
to
invocationBuilderAuth.header(HttpHeaders.AUTHORIZATION, "Basic " + loginValue);
Out of the box, the HttpClient doesn’t do preemptive authentication. If you get totally stuck you can try a variation on Basic auth called "preemptive auth" using AuthCache and BasicScheme (not used with a default basic auth).
Related
Hello I am trying to pass authorization token in rest assured using rest assured specification class. But I am getting authentication failed message below is my code.
String Jsonbody="{\"name\":\"Vishwamitra Pillai\",\r\n"
+ "\"email\":\"pillai_vishwamitra#schmitt.info24\",\r\n"
+ "\"gender\":\"female\",\"status\":\"active\"}";
String token="038f2fd3b9431b5fb34a889c9b4bf8eb29bcb72b16ea02535a151106bf94eff7";
String authToken="Bearer"+token;
RequestSpecBuilder reqSpeBuilder;
final RequestSpecification reqSpec;
reqSpeBuilder = new RequestSpecBuilder();
reqSpeBuilder.setBaseUri("https://gorest.co.in");
reqSpeBuilder.addHeader("Authorization", authToken);
reqSpec = reqSpeBuilder.build();
RestAssured.given().spec(reqSpec).body(Jsonbody).
when().post("/public/v2/users").then().log().all().statusCode(201);
Can you please try and add the content type for the request
reqSpeBuilder.addHeader("Content-Type", "application/json");
also try and change the response to
RestAssured.given().spec(reqSpec).body(Jsonbody).
when()
.contentType(ContentType.JSON)
.post("/public/v2/users").then().log().all().statusCode(201);
You can simply add it as header.
reqSpeBuilder.addHeader("Authorization", authToken);
Your problem is here:
String authToken="Bearer"+token;
It should be like this:
String authToken= "Bearer " + token;
You have missed on space between Bearer and the actual token.
I'm trying to access a REST webservice from SalesForce from my java application.
I'm using Jersey to make the webservice call.
private String getRegisterId(String registerName, String accessToken) throws JSONException, BusinessException {
ClientConfig config = new DefaultClientConfig();
config.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
Client client = Client.create(config);
WebResource wr = client.resource(salesforeceUrl + "/data/v31.0/query");
JSONObject register = wr //
.queryParam("q", "SELECT+Id+FROM+HealthData_Register__c+WHERE+name+=+'" + registerName + "'+AND+IsDeleted+=+false") //
.header(HttpHeaders.AUTHORIZATION.getValue(), "Bearer " + accessToken) //
.get(JSONObject.class);
JSONArray records = register.getJSONArray("records");
return records.getJSONObject(0).getString("Id");
}
The problem I have is that Jersey is so nice that it changes the + symbol to %2B and the + symbol to %3D for my queryParam but SalesForce doesn't like this.
It also does this for the header. If my accessToken contains a special character I will get an 401 (UNAUTHORIZED) response.
Is there a way to ask Jersey to not make special symbols url-safe?
Since it's a GET request it's correct that the query params are url-encoded.
Why do you put the symbol + instead of spaces in the query? Did you try putting just the spaces? Is really the server expecting a + symbol instead of spaces?
i need to connect to a rest service to get the user id by using a token.
List<Object> providers = new ArrayList<>();
providers.add(new JacksonJaxbJsonProvider());
client = WebClient.create(properties.getProperty(URL), providers);
client = client.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE);
client.path(PATH + token);
Response response = client.get();
The entity of response have this format:
{"message":"Token is valid","userId":1}
To get the userId, i have:
response.readEntity(AuthResponse.class).userId;
It is possible to take only the userId without creating an class with that format ? (without AuthResponse.class)
You can try to read your JSON as Map, for example: response.readEntity(Map.class).get("userId")
Please refer to this page for more information.
I want to send the data to person object. How to do it with PostMethod.
def payload ='<person><nationalId>'+1234567+'</nationalId></person>'
def method = new PostMethod(url)
def client = new HttpClient()
payload = payload.trim()
method.addRequestHeader("Content-Type","text/xml")
method.addRequestHeader("Accept","text/xml,application/xml;q=0.9")
Credentials credentials = new UsernamePasswordCredentials('simple', 'simple');
client.getState().setCredentials(new AuthScope(AuthScope.ANY_HOST,8080, AuthScope.ANY_REALM, "digest"),credentials);
method.setRequestEntity(new StringRequestEntity(payload))
def statusCode = client.executeMethod(method)
println "STATUS CODE : ${statusCode}"
def resultsString = method.getResponseBodyAsString()
method.releaseConnection()
println resultsString
I tried above coding. How to set password and username and password digest also. For that i think status code 400 is coming.Please notify where i made mistake
Try to look at REST Client Builder Plugin. See docs and I guess, you'll find more convenient way to send request
I want to add post to my blog using Blogger API. I successfully got rights to use Blogger API and activated them in Google API console. I used this tutorial to obtain access_token. I found this question , so before ever request I obtain new request_token.
When I make first request to add post, I got en error: 401 "message": "Invalid Credentials", "location": "Authorization".
When I make second request to add post with new token, I got error: 403 "message": "Daily Limit Exceeded. Please sign up"
Code for my request is:
final JSONObject obj = new JSONObject();
obj.put("id", mUserID);
final JSONObject requestBody = new JSONObject();
requestBody.put("kind", "blogger#post");
requestBody.put("blog", obj);
requestBody.put("title", msg[0]);
requestBody.put("content", msg[0] + " " + msg[1]);
final HttpPost request = new HttpPost("https://www.googleapis.com/blogger/v3/blogs/" + mUserID + "/posts");
request.addHeader("Authorization", "Bearer " + mToken);
request.addHeader("Content-Type", "application/json");
request.setEntity(new StringEntity(requestBody.toString()));
final HttpResponse response = mHttpClient.execute(request);
final HttpEntity ent = response.getEntity();
Log.i(SocialPoster.LOG, EntityUtils.toString(ent));
ent.consumeContent();
UPDATE
Solution was found: simply adding "?key={MY_API_KEY}" to request's URL solved the problem
The Tutorial site you linked states
"The API Key is mandatory as it identifies your application and therefore allows the API to deduct quota and use the quota rules defined for your project. You need to specify the API Key on your Tasks service Object."
useTasksAPI(String accessToken) {
// Setting up the Tasks API Service
HttpTransport transport = AndroidHttp.newCompatibleTransport();
AccessProtectedResource accessProtectedResource = new GoogleAccessProtectedResource(accessToken);
Tasks service = new Tasks(transport, accessProtectedResource, new JacksonFactory());
service.accessKey = INSERT_YOUR_API_KEY;
service.setApplicationName("Google-TasksSample/1.0");
// TODO: now use the service to query the Tasks API
}
Sounds to me like you are missing the API key, using it wrong, misplaced it in your code or supplied it to the service in the wrong way.
I haven't looked over the code here, but this is Google's sample code for what you are trying to do. Test your API key with this code.