Im trying to refresh an Access token in my application following this solution.
My actual problem is handling the callback and then return the new request in the authenticate method.
I tried using an interface to return a String from my callback method but then I cant assign it to a variable, nor can I return the new request from there since its inside my onResponseListener.
How can I solve this issue?
public Request authenticate(Route route, Response response) throws IOException {
// GetAuthRequest is a void method, and I cant assign a String value on the callback.
getAuthRequest(new AuthResponse() {
#Override
public Request onSuccess(String token) {
return response.request().newBuilder()
.header("Authorization", "Bearer " + token)
.build();
}
});
I was using an Asynchronous call instead of Synchronous. Ended up making a method that returns an String like so:
private String getAuthRequest() {
// Make the request above
try (Response response = httpClient.newCall(request).execute()) {
JSONObject jsonObject = new JSONObject(response.body().string());
return jsonObject.getString("access_token");
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return null;
}
Related
Friends!
I have a simple HTTP request:
void postRequest(String postUrl,String phone, String message) throws IOException {
OkHttpClient client = new OkHttpClient();
//RequestBody body = RequestBody.create(JSON, postBody);
RequestBody body = new FormBody.Builder()
.add("phone", phone)
.add("message", message)
.build();
Request request = new Request.Builder()
.url(postUrl)
.post(body)
.build();
//System.out.println(request);
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
call.cancel();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
Log.d("TAG",response.body().string());
}
});
}
How to properly implement sending a JSON object instead of simple parameters?
My attempts were unsuccessful, so I really need a hint.
The server that will accept JSON is running on AKKA-HTTP.
How do I send a request to this server correctly?
final case class Message(phone: String, message: String, service: String)
implicit val item = jsonFormat3(Message)
val queue: Queue[Message] = Queue()
val addMessage = post {
path("add_message"){
parameters("phone".as[String], "message".as[String], "service".as[String]){
(phone, message, service) => {
queue.enqueue(Message(phone, message, service))
complete("ok")
}
}
}
}
The easiest way to map and serialize your object in JSON format is to use the ObjectMapper class of jackson-databind library.
I personally use it to implement integration tests of RestControllers and it works very well. Here is the utility class I realized, you can take it and use it for your purposes:
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public final class JsonUtils {
public static String json(Object obj) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.writeValueAsString(obj);
}
}
What you need to have is a POJO class which implements Serializable, and then pass the instance of your class to the json method and it will return the JSON format.
You can definitely use it for Android projects. I found many examples where you can add the dependency, but it depends whether you use Gradle or Maven.
Try that out!!!
How do you like this option?
I tried to implement it, but the send fails.
I'm missing an important detail. But I don't understand what it is.
// create your json here
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("KEY1", "VALUE1");
jsonObject.put("KEY2", "VALUE2");
} catch (JSONException e) {
e.printStackTrace();
}
OkHttpClient client = new OkHttpClient();
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
// put your json here
RequestBody body = RequestBody.create(JSON, jsonObject.toString());
Request request = new Request.Builder()
.url("https://YOUR_URL/")
.post(body)
.build();
Response response = null;
try {
response = client.newCall(request).execute();
String resStr = response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
In my app I am using netflix zuul to route a request from a microservice (gateway) to another. The requests are being routed fine but I also want to introduce some parameters in the request body before it is routed to the appropriate microservice. For this I am using Zuul pre filter like this.
public class SimpleFilter extends ZuulFilter {
private static Logger log = LoggerFactory.getLogger(SimpleFilter.class);
#Override
public String filterType() {
return "pre";
}
#Override
public int filterOrder() {
return 1;
}
#Override
public boolean shouldFilter() {
return true;
}
#Override
public Object run() {
try {
RequestContext context = RequestContext.getCurrentContext();
InputStream in = (InputStream) context.get("requestEntity");
if (in == null) {
in = context.getRequest().getInputStream();
}
String body = StreamUtils.copyToString(in, Charset.forName("UTF-8"));
// body = "request body modified via set('requestEntity'): "+ body;
body = body.toUpperCase();
context.set("requestEntity", new ByteArrayInputStream(body.getBytes("UTF-8")));
} catch (IOException e) {
log.error(e.getMessage(), e);
}
return null;
}
}
For now I am just trying to change the body to upper case but the microservice to which this request is routed doesn't receive the modified body (upper case). Instead it receives the original one. Am I doing something wrong. Any help would be appreciated. Thanks !!
Was able to do the following - transform a GET request to a POST request, and add body content to the (proxied) POST request.
public Object run() throws ZuulException {
RequestContext context = RequestContext.getCurrentContext();
context.addZuulRequestHeader("Content-Type", "application/x-www-form-urlencoded");
String body = String.format("a=%s&b=%s", a, b);
final byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
context.setRequest(new HttpServletRequestWrapper(context.getRequest()) {
#Override
public ServletInputStream getInputStream() {
return new ServletInputStreamWrapper(bytes);
}
#Override
public int getContentLength() {
return bytes.length;
}
#Override
public long getContentLengthLong() {
return bytes.length;
}
#Override
public String getMethod() {
return "POST";
}
});
return null;
}
try this one It's may be work in your case .
requestContext.getCurrentContext().put("requestEntity", new ByteArrayInputStream(body.getBytes("UTF-8")));
Turned out this method cannot change the request body within the requestContext. Truly in the requestContext, a new field "requestEntity" is added, however, the request body from context.getRequest().getInputStream() remains the same after this operation.
You can modify the request body, see this answer for an example. You just need to wrap the new request data and make sure you correctly report it's new content length.
When I fail to parse the json from the server, I try to collect the situation.
I can see what the server gave me using the class that implements the Interceptor.(LoggingInterceptor)
However, I do not seem to be able to get the value in 'onFailure()', a situation where I need to collect errors. Because it only provides 'Call' and 'Throwable'. How do I get raw data from the server in 'onFailure()'?
Below is my code.
LoggingInterceptor
public class LoggingInterceptor implements Interceptor {
//로그에 쓰일 tag
private static final String TAG = CalyApplication.class.getSimpleName() + "/" + LoggingInterceptor.class.getSimpleName();
#Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
long t1 = System.nanoTime();
Response response = chain.proceed(request);
long t2 = System.nanoTime();
String responseString = new String(response.body().bytes());
//yes, I can see response in here. but I need it in 'onFailure()'.
Logger.i(TAG, "code : " + response.code() + "\n" + responseString);
return response.newBuilder()
.body(ResponseBody.create(response.body().contentType(), responseString))
.build();
}
}
Actrivity
void fetchData(){
ApiClient.getService().test(
"test"
).enqueue(new Callback<BasicResponse>() {
#Override
public void onResponse(Call<BasicResponse> call, Response<BasicResponse> response) {
BasicResponse body = response.body();
switch (response.code()){
case 200:
break;
default:
break;
}
}
#Override
public void onFailure(Call<BasicResponse> call, Throwable t) {
//I want get Response object in here!
//but it only provides Call&Throwable
}
});
}
Thanks!
If you get a 4xx or 5xx (error)status code then the onResponse is called, not the onFailure. You get a response body(2xx) or error body accordingly only if the call was successful. So in onResponse you should have the following structure:
if (response.isSuccessful()) {
// Get response body
} else if (response.errorBody() != null) {
// Get response errorBody
String errorBody = response.errorBody().string();
}
Edit: More info about how to retrieve the errorBody can be found here.
I am making a weather app by using the wunderground API. I am also using Retrofit2 and GSON library.
Here is the API URL format to get the JSON response:
http://api.wunderground.com/api/API_KEY/conditions/q/ISO_COUNTRY_CODE/CITY_NAME.json
I've declared an java API_Interface as follows:
public interface API_Interface {
#GET("/api/{apikey}/conditions/q/BD/{city}.json")
Call<CurrentObservation> getCurrentWeather(
#Path("apikey") String apikey,
#Path("city") String city);
}
And trying to pass the apikey and city from the MainActivity as follows:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
API_Interface weatherService = retrofit.create(API_Interface.class);
Call<CurrentObservation> call = weatherService.getCurrentWeather(Constants.API_KEY,"Dhaka");
call.enqueue(new Callback<CurrentObservation>() {
#Override
public void onResponse(Call<CurrentObservation> call, Response<CurrentObservation> response) {
textView.setText(response.body().toString());
Log.d("result",response.body().toString());
}
#Override
public void onFailure(Call<CurrentObservation> call, Throwable t) {
textView.setText("Something went wrong: " + t.getMessage());
Log.e("error",t.getMessage());
}
});
Here is the Constant class:
public class Constants {
public static final String BASE_URL="http://api.wunderground.com";
public static final String API_KEY="b5efba6dc63cc1b1";
}
and here is the POJO Model of CurrentObservation class: http://paste.ubuntu.com/22291964/
I've overriden a toString() method in the model.
There are some other POJO classes-
But this approach gives null response as following-
Weather Status: null
Pressure: null
Humidity: null
Temperature: null
Here is the actual JSON response from the API URL- http://paste.ubuntu.com/22292683/
How do I pass the parameters into #GET to get the correct response?
Your base URL should look like this:
http://blah.com/api/blah/
And your #GET method should have an URL like this
api/{apikey}/conditions/q/BD/{city}.json
EDIT: You might have onResponse called with an error body. Please adjust the following code for your use-case:
public static boolean handleError(Retrofit retrofit, Response<?> response) {
if(response != null && !response.isSuccessful() && response.errorBody() != null) {
Converter<ResponseBody, ErrorResponse> converter = retrofit.responseBodyConverter(ErrorResponse.class, new Annotation[0]);
try {
ErrorResponse errorResponse = converter.convert(response.errorBody());
// do something
} catch(IOException e) {
Log.e(TAG, "An error occurred", e);
}
return true;
}
return false;
}
You can do it like that:
#GET
Call<CurrentObservation> getCurrentWeather(#Url String url);
I use this to config my retrofit:
RestAdapter restAdapter = new RestAdapter.Builder()
//add headers to requests
.setRequestInterceptor(getAuthenticatedRequestInterceptor())
.setEndpoint(BASE_URL)
.setConverter(new GsonConverter(getGson()))
.build();
and The getAuthenticatedRequestInterceptor() method adds headers to request:
public AccountRequestInterceptor getAuthenticatedRequestInterceptor() {
AccountRequestInterceptor interceptor = new AccountRequestInterceptor();
Map<String, String> headers = new HashMap<>();
String accessToken = null;
try {
accessToken = TokenProvider.getInstance(mContext).getToken();
} catch (InterruptedException e) {
}
headers.put(HeadersContract.HEADER_AUTHONRIZATION, O_AUTH_AUTHENTICATION + accessToken);
interceptor.setHeader(headers);
return interceptor;
}
getToken() method is:
private synchronized string getToken() throws InterruptedException {
if (!isRefreshing()) {
//This is very important to call notify() on the same object that we call wait();
final TokenProvider myInstance = this;
setRefreshing(true);
MyApplication.getRestClient().getAccountService().getRefreshedToken(mLoginData.getRefreshToken())
.subscribe(new Observer<LoginResponse>() {
#Override
public void onCompleted() {
synchronized (myInstance) {
setRefreshing(false);
myInstance.notifyAll();
}
}
#Override
public void onError(Throwable e) {
synchronized (myInstance) {
setRefreshing(false);
myInstance.notifyAll();
}
}
#Override
public void onNext(LoginResponse loginResponse) {
synchronized (myInstance) {
mLoginData = loginResponse;
mAccountProvider.saveLoginData(loginResponse);
myInstance.notifyAll();
}
}
});
}
this.wait();
return mLoginData.getToken();
}
The TokenProvider.getInstance(mContext).getToken() has a wait() on main thread to get the response from an async method and i know that is a bad thing to do but i need this here to wait for the response to take the token from it and then return the token.how can i do this in a separate thread to avoid waiting on the main thread?
Note:
1 - that this is called before any request with retrofit.
2 - I read this and i know i can refresh token after a fail request, but for business reasons i want to avoid having an invalid token.
3 - I call MyApplication.getRestClient().getAccountService().login(loginRequest,callback...) in my Activity and before adding token everything happened in background thread. so I want to use my token and do not block the main thread.
UPDATE: I added the following Interceptor to my new OkHttp:
public class RequestTokenInterceptor implements Interceptor {
#Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request request = chain.request();
Request newRequest;
try {
Log.d("addHeader", "Before");
String token = TokenProvider.getInstance(mContext).getToken();
if (token != null) {
newRequest = request.newBuilder()
.addHeader("Bearer", token)
.build();
} else {
// I want to cancel the request or raise an exception to catch it in onError method
// of retrofit callback.
}
} catch (InterruptedException e) {
Log.d("addHeader", "Error");
e.printStackTrace();
return chain.proceed(request);
}
Log.d("addHeader", "after");
return chain.proceed(newRequest);
}
}
Now how can i cancel the request or raise an exception to catch it in onError method of retrofit callback, if token is null?
It's a little bit strange issue but let me try to help you. :)
As you know you can refresh token after a failed request with retrofit using response interceptor.
Let's try to use interceptor before request.
public class RequestTokenInterceptor implements Interceptor {
#Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
// Here where we'll try to refresh token.
// with an retrofit call
// After we succeed we'll proceed our request
Response response = chain.proceed(request);
return response;
}
}
And when you're creating your api create a new HttpClient:
OkHttpClient client = new OkHttpClient();
client.interceptors().add(new RequestTokenInterceptor());
And add your http client to your adapter like below:
.setClient(new OkClient(client))
If this works, before every request you'll try to refresh token first and then will proceed your api request. So in ui there'll be no difference with your normal api calls.
Edit:
I'm editing my answer too. If you want to return an error in else case if token null, in else case you can create your custom response:
private Response(Builder builder) {
this.request = builder.request;
this.protocol = builder.protocol;
this.code = builder.code;
this.message = builder.message;
this.handshake = builder.handshake;
this.headers = builder.headers.build();
this.body = builder.body;
this.networkResponse = builder.networkResponse;
this.cacheResponse = builder.cacheResponse;
this.priorResponse = builder.priorResponse;
}
or simply you can return a null response. if you build your custom response and set your code not to 200 such as 401 or 400+ you'll receive that response in Retrofit's callbacks failure method. Than you can do what ever you want.
If you return null you'll get a RuntimeException i think and still you can catch response in your callback's failure method.
After you create your own response in else you can create your custom callback and catch your null response and transform your custom error how ever you want like below:
public abstract class DefaultRequestCallback<T> implements Callback<T> {
public abstract void failure(YourCustomException ex);
public abstract void success(T responseBean);
#Override
public void success(T baseResponseBean, Response response) {
if (response == null) {
// Here we catch null response and transform it to our custom Exception
failure(new YourCustomException());
}
} else {
success(baseResponseBean);
}
}
#Override
public void failure(RetrofitError error) {
// Here's your failure method.
// Also you can transform default retrofit errors to your customerrors
YourCustomException ex = new YourCustomException();
failure(ex);
}
}
This can help you i think.
Edit 2:
You can build a new Response like below. There's a builder pattern in Retrofit's Response class. You can check it from there.
Response response = new Response.Builder().setCode(401).setMessage("Error Message").build();
You could make all long actions in AsyncTask doInBackground method, while in onPre- and onPostExecute you could show/hide some progress bars when user is waiting
Ok, I think if you are calling your getAuthenticatedRequestInterceptor() on the main thread and which in turns call getInstance(),in which i feel you would be creating an object of Type TokenProvider hence when you create this object in the main thread your object.wait() runs on main thread hence to run this on a background thread probably modify your getAuthenticatedRequestInterceptor() method to execute the following lines in a new thread.
try {
accessToken = TokenProvider.getInstance(mContext).getToken();
} catch (InterruptedException e) {
}
headers.put(HeadersContract.HEADER_AUTHONRIZATION, O_AUTH_AUTHENTICATION + accessToken);
interceptor.setHeader(headers);
return interceptor;
but this will have problems for notifying your RestAdapter as the main thread will proceed executing, hence i would suggest
you call getAuthenticatedRequestInterceptor() method first in a new thread and then notify your main thread to build your RestAdapter.This will free your main thread but with the strategy you are employing you will have to wait until you receive the token to make any calls.