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.
Related
I try to put data from the NewOrderRequest(pojo) class into the parameters :
#Query("params") NewOrderRequest params
but I get this result:
resultQueryString: params com.example.city.Model.NewOrderRequest#f45c8ad
expectation result:
resultQueryString: params +911
Data setting:
NewOrderRequest newOrderRequest = new NewOrderRequest();
newOrderRequest.setPhone("+911");
NetworkService.getInstance()
.service()
.newOrder(newOrderRequest)
Request:
#Headers({"Accept:application/json", "Content-Type:application/json;"})
#POST("RemoteCall?method=Taxi.WebAPI.NewOrder")
Call<RegResponse>newOrder(#Header("Cookie") String setCookie,#Query("params") NewOrderRequest params);
Please tell me how to pass the phone to the parameter?
You are sending an Object in #Query param, Only #Body accepts the object as its param. What you want is to convert your Object into JsonObject. I assume you're using Gson Library.
NewOrderRequest newOrderRequest = new NewOrderRequest();
newOrderRequest.setPhone("+911");
NetworkService.getInstance()
.service()
.newOrder(new Gson().toJson(newOrderRequest))
Try below code
#Headers({"Accept:application/json", "Content-Type:application/json;"})
#POST("RemoteCall?method=Taxi.WebAPI.NewOrder")
Call<RegResponse>newOrder(#Header("Cookie") String setCookie,#Query("params") String phone);
As it is a post request, and the intention is to send the data as an json object, the data is better sent in the request body rather than query param. Also any sensitive details should be part of request body.
I want to consume a rest service which returning bunch of values.
The bean look like follows.
Class Customer{
Name, Address, Age ---etc // Almost 200 fields are there. Including reference to many objects as well. So it is very hard to create a bean for accepting the response.
}
Is there any alternative way to consume the response.
Customer customer = restTemplate.getForObject(http://testurl);
This is not I need. I need any other way to consume the service without creating the bean.
Using Spring Boot,Java 8
You probably might want to try to get JSONObject on your client side if you don't want to create a heavyweight DTO. Something along the lines:
String str = restTemplate.getForObject("http://testurl", String.class);
JSONObject myCustomer = new JSONObject(str);
String name = myCustomer.getString("name");
JSONObject address = myCustomer.getJSONObject("address"); // if address is a composite object with city, street, etc...
You could get the response in a JSON format and use JSONObject class to extract the data.
Example:
String response = restTemplate.getJSONObject(http://testurl);
JSONObject params = new JSONObject(response);
if(params.has("Name"))
String customerName = params.getString("Name");
I was querying and getting data from database using Spring jdbctemplate rowmapper. Once I get the data I was mapping it to a Java object and converting it to a json object.
My json object contains contains a object with 2 fields
code
status
When I was getting the data from database I was passing 200 and success data to the above 2 fields and passing the json object as web service response.
My actual question is even if I didn't get any data, I need to pass the json object as web service response but with code as "404" amd message field as "no data" and other fields are to be empty strings ("") , similarly if any exception occurred, need to send json object with empty strings but with 503 code.
How can I do that?
My method code snippet:
userdtls= userDaoimpl.getUserdetails(userId);
if (userdtls== null) {
ResponseBuilder builder = Response.ok(convertToJson(userdtls),MediaType.APPLICATION_JSON).status(Status.NOT_FOUND).entity("No such user " + userdtls+);
throw new WebApplicationException(builder .build());
}
convertToJson.java
public String convertToJson(UserData userdtls) {
StatusData status = new StatusData ();
status.setCode("200");
status.setMessage("Success");
userdtls.setStatus(status);
PersonalData personal = new PersonalData();
personal.setdob("june11");
personal.setage("28");
userdtls.setPersonal(personal);
Gson gson = new GsonBuilder().serializeNulls().create();
return gson.toJson(userdtls));
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
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.