Blogger JSON API add a post - java

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.

Related

How to pass authorization token in request using Request Specification Class in Rest assured API testing. How to use rest specification builder class

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.

Unable to authorize in API Basic Authentication in Java

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).

Getting one field from response entity json

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.

How to access wsdl in grails - 400 status code return

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

Yahoo Oauth inconsistent "Invalid Signature"

H!I am having a very hard time with Yahoo Oauth right now.
So here's the problem, I am using scribe 3.1.5 and followed Yahoo's documentations(apparently they use Oauth1.0), I've been able to get the request token, then trade for the access token with the verifier. The problem emerges when I try to get user's GUID from URL http://social.yahooapis.com/v1/me/guid?format=json with the access token.
now, what's interesting is that, yahoo would sometimes give me the GUID back, and sometimes give me a "invalid signature" error. Sometimes I get 5 invalid signatures in a row, sometimes I get 15 successful calls in a row, most of the time it is like 40% invalid signatures and 60% success. What is even weirder is that sometimes I get a success when fetching GUID, but when i try to fetch user's profile IMMEDIATELY after the success with the identical access token and GUID, it gives me an invalid sigature...(wtf)
so here's the code I use:
Redirecting User:
Token requestToken = yahooService.getRequestToken();
getSession().setAttribute("yahooRequestToken", requestToken);
String authenticationUrl = yahooService.getAuthorizationUrl(requestToken);
redirect(authenticationUrl);
Getting callback:
#GET #Path("/oauthcallback/yahoo")
public Response yahooCallback(#QueryParam("oauth_token") String oAuthToken, #QueryParam("oauth_verifier") String oAuthVerifier) {
Token requestToken = (Token)getSession().getAttribute("yahooRequestToken");
Token accessToken = yahooService.getAccessToken(requestToken, oAuthVerifier);
UserProfile user = userService.findUserById(getUserId());
try{
//TODO occasioanlly yahoo returns invalid_signature, this is inconsistent and I have no idea why
String guid = yahooService.getGuid(accessToken);
String email = yahooService.getUserEmail(guid, accessToken);
.....
YahooService::Getting Access Token:
[the service object is protected final OAuthService service; in parent class]
#Override
public Token getAccessToken(Token requestToken, String oAuthVerifier) {
Verifier verifier = new Verifier(oAuthVerifier);
return service.getAccessToken(requestToken, verifier);
}
YahooService::Getting GUID:
#Override
public String getGuid(Token accessToken){
OAuthRequest requestA = new OAuthRequest(Verb.GET, GET_YAHOO);
service.signRequest(accessToken, requestA);
Response responseA = requestA.send();
JsonParser parser = new JsonParser();
//sometimes the response body is a invalid signature error message
JsonObject json = (JsonObject)parser.parse(responseA.getBody());
return json.getAsJsonObject("guid").get("value").getAsString();
}
YahooService::Getting User Email:
#Override
public String getUserEmail(String guid, Token accessToken) {
String profileCallUrl = GET_YAHOO_PROFILE.replaceAll("GUID", guid);
OAuthRequest requestB = new OAuthRequest(Verb.GET, profileCallUrl);
service.signRequest(accessToken, requestB);
requestB.addHeader("realm", "yahooapis.com");
Response responseB = requestB.send();
JsonParser parser = new JsonParser();
//sometimes the response body is a invalid signature error message
JsonObject jsonProfile = (JsonObject)parser.parse(responseB.getBody());
...processing code, error free
}
I know YahooAPI class in Scribe 3.1.5 in maven distribution is like 2 years old, but I doubt it would lead to such inconsistent behavior. Scribe's built in support for Google and Live oauth is basically useless, unfortunately, unlike Google or Hotmail which both have awesome doc so that I could basically figure out everything myself, Yahoo's doc stops at getting the access token, I can not find useful explanation on why I would get an invalid signature SOMETIMES with my access token
Please help! Thanks in advance
Its looks like Yahoo issue, I have same error message since few days :
http://developer.yahoo.com/forum/OAuth-General-Discussion-YDN-SDKs/signature-invalid-when-making-calls-to-the/1385735171123-8a38d8cf-815b-43ac-9d77-5bd2f2f60796
There is no need to ask for GUID to yahoo as yahoo returns GUID of the currently logged in user at the time of giving you the access token so if you have a access token you also have a GUID in the response.
Refer this

Categories