Dinamic headers in Retrofit (1-2) do not work - android

I'm trying to make authtoken GET request to my server.
I'm trying to do in like this:
public interface FixedRecApi {
public static final String ENDPOINT = "http://******.pythonanywhere.com/";
//#Headers("Authorization: Token ce7950e8d0c266986b7f972407db898810322***") this thing work well!!
#GET("/auth/me/")
Observable<User> me(#Header("Authorization: Token") String token); //this does not work at all!
Observable<User> me();
}
So as you see, the line with explicit header: #Headers - works perfect.
But when I try to pass it as a parameter - it says "no credentials provided".
My application onCreate:
#Override
public void onCreate() {
super.onCreate();
ActiveAndroid.initialize(this);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(FixedRecApi.ENDPOINT)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(
GsonConverterFactory.create(new GsonBuilder()
.excludeFieldsWithModifiers(Modifier.FINAL, Modifier.TRANSIENT, Modifier.STATIC)
.excludeFieldsWithoutExposeAnnotation()
.serializeNulls()
.create()))
.build();
service = retrofit.create(FixedRecApi.class);
}
Have no idea what is wrong with this thing. Interceptors don't work either...

I've found the solution. Headers consist of two parts:
header name: "Authrorization"
then colon
header value: "Token ce7950e8d0c266986b7f972407db898810322***"
So, Retrofit usage should be:
Observable<User> me(#Header("Authorization") String token);
and then for example in MainActivity:
RetrofitApi.me("Token " + "ce7950e8d0c266986b7f972407db898810322***");

Related

How to view created JSON string using Retrofit

I am not sure if this is a silly question (hence why I am unable to find the answer) but I was wondering if it is possible to Toast or Log output the created JSON that is being sent to the server, when it is sent.
I am simply interested to see the created JSON - I am using the following method, which is using Retrofit and .addConverterFactory(GsonConverterFactory.create(gson)):
private void addTeamMember(final List teamMemberArray,final String team_id) {
//helps with debugging regarding post requests
Gson gson = new GsonBuilder()
.setLenient()
.create();
//Retrofit is a REST Client for Android and Java by Square.
//It makes it relatively easy to retrieve and upload JSON (or other structured data) via a REST based webservice
Retrofit retrofit = new Retrofit.Builder()
//directing to the localhost which is defined in the Constants Class as BASE_URL
.baseUrl(Constants.BASE_URL)
//Add converter factory for serialization and deserialization of objects.
//Gson passed as a parameter to help with debug
.addConverterFactory(GsonConverterFactory.create(gson))
//Create the Retrofit instance using the configured values.
.build();
//The Retrofit class generates an implementation of the RequestInterface interface.
RequestInterface requestInterface = retrofit.create(RequestInterface.class);
for (Object x : teamMemberArray) {
//create new Team object
TeamMember teamMember = new TeamMember();
//setter
teamMember.setFullName(String.valueOf(x));
teamMember.setTeam_id(team_id);
Toast.makeText(getActivity(), teamMember.getFullName(),
Toast.LENGTH_LONG).show();
//create new server object
final ServerRequest request = new ServerRequest();
//make a request to set the operation to Team_Member
request.setOperation(Constants.Team_Member);
//set values entered for the new teamMember to be sent to the server
request.setTeamMember(teamMember);
Call<ServerResponse> response = requestInterface.operation(request);
/**
* Enqueue is used to Asynchronously send the request and notify callback of its response or if an error occurred
* talking to the server, creating the request, or processing the response.
*/
response.enqueue(new Callback<ServerResponse>() {
#Override
public void onResponse(Call<ServerResponse> call, retrofit2.Response<ServerResponse> response) {
ServerResponse resp = response.body();
/*Snackbars provide lightweight feedback about an operation. They show a brief message at the
bottom of the screen on mobile and lower left on larger devices. Snackbars appear above all other
elements on screen and only one can be displayed at a time.
*/
Snackbar.make(getView(), resp.getMessage(), Snackbar.LENGTH_LONG).show();
if (resp.getResult().equals(Constants.SUCCESS)) {
SharedPreferences.Editor editor = pref.edit();
Log.d("TEST VALUE", "getTeamMemberName() = " + response.body().getTeamMember().getFullName() );
Log.d("TEST VALUE", "getTeamMemberUniqueID() = " + response.body().getTeamMember().getUnique_id());
Log.d("TEST VALUE", "getTeamMemberTeamID() = " + response.body().getTeamMember().getTeamID());
editor.putString(Constants.FULL_NAME, resp.getTeamMember().getFullName());
editor.putString(Constants.UNIQUE_ID, resp.getTeamMember().getUnique_id());
editor.putString(Constants.TEAM_ID, resp.getTeamMember().getTeamID());
editor.apply();
goToQuestions();
}
progress.setVisibility(View.INVISIBLE);
}
#Override
public void onFailure(Call<ServerResponse> call, Throwable t) {
progress.setVisibility(View.INVISIBLE);
Log.d(Constants.TAG, "failed" + t);
Snackbar.make(getView(), t.getLocalizedMessage(), Snackbar.LENGTH_LONG).show();
}
});
}
}
My reasoning is that if I could see the JSON being sent across, it will help me with debugging when using Postman.
You can use OkHttpInterceptor for logging network calls with Retrofit. It will intercept any call and show logs in logger.
Add dependecy in your gradle:
compile 'com.squareup.okhttp3:logging-interceptor:3.8.0'
Then before setting your retrofit client use:
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(Level.BASIC);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(logging)
.build();
And finally add in retrofit:
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
Add this in dependencies
compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
and ApiClient
public class ApiClient {
public static final String BASE_URL = "URL";
private static Retrofit retrofit = null;
public static Retrofit getClient() {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
final OkHttpClient okHttpClient = new OkHttpClient.Builder()
.readTimeout(300, TimeUnit.SECONDS)
.connectTimeout(300, TimeUnit.SECONDS)
.addInterceptor(logging)
.build();
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}

Retrofit2 - Can't get basic authentication for webAPI with dynamic URL

I'm familiar with how to use dynamic URLs with Retrofit2 but having issue sending username & password in the request. The webAPI works by entering a URL, a login prompt appears on the screen for a username & password, after authentication a JSON response is displayed. The interface is defined for a dynamic URL:
#GET
public Call<User> getJSON(#Url String string);
My request is as follows:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(API_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
LoginService service = retrofit.create(LoginService.class);
Call<User> call = service.getJSON("https://username:password#api.url.com/");
call.enqueue(new Callback<User>() {
#Override
public void onResponse(Call<User> call, retrofit2.Response<User> response) {
System.out.println("Response status code: " + response.code());
I'm certain the URL is correct as it works in the browser & but I keep getting error the username & password aren't correct?
I/System.out: Response status code: 401
Also, as far as I can tell I can only use #GET rather than #POST because whenever I try #POST the response code is:
I/System.out: Response status code: 405
At first I tried to follow something similar to this post using an encoded flag because it's an example of how to use #PATH & #URL with Retrofit2 but didn't have any success. That's why I tried the username:password# prepend to the URL. Most of the other examples all use the #POST method.
Any feedback or ideas on how I can authenticate? Thanks
Not sure how to do it in retrofit, but you can add it via an OkHttp interceptor --
OkHttpClient client = new OkHttpClient().newBuilder().addNetworkInterceptor(
new Interceptor() {
#Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request request = chain.request();
HttpUrl url = request.url();
url = url.newBuilder().username("username").password("password").build();
Request newRequest = request.newBuilder().url(url).build();
return chain.proceed(newRequest);
}
}
).build();
be sure to add this client to your retrofit instance --
Retrofit retrofit = new Retrofit.Builder()
.client(client)
.baseUrl(API_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
Another way to use basic authentication with Retrofit2 would be to pass the authentication string as an argument to your interface method.
So you would change the method signature to:
#GET
public Call<User> getJSON(#Url String string, #Header("Authorization") String myAuthString);
And then call it like this:
Call<User> call = service.getJSON("https://api.url.com/", "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==");
Where you substitute QWxhZGRpbjpvcGVuIHNlc2FtZQ== for your Base64-encoded username:password string.
If you need to pass the username and password for every API call and want to keep the method signatures clean, it might be better to use the custom OkHttpInterceptor method instead.

Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $

What is this error ? How can I fix this? My app is running but can't load data. And this is my Error: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $
This is my fragment :
public class news extends Fragment {
private RecyclerView recyclerView;
private ArrayList<Deatails> data;
private DataAdapter adapter;
private View myFragmentView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myFragmentView = inflater.inflate(R.layout.news, container, false);
initViews();
return myFragmentView;
}
private void initViews() {
recyclerView = (RecyclerView) myFragmentView.findViewById(R.id.card_recycler_view);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(layoutManager);
data = new ArrayList<Deatails>();
adapter = new DataAdapter(getActivity(), data);
recyclerView.setAdapter(adapter);
new Thread()
{
public void run()
{
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
loadJSON();
}
});
}
}
.start();
}
private void loadJSON() {
if (isNetworkConnected()){
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(interceptor)
.retryOnConnectionFailure(true)
.connectTimeout(15, TimeUnit.SECONDS)
.build();
Gson gson = new GsonBuilder()
.setLenient()
.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://www.memaraneha.ir/")
.client(client)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
RequestInterface request = retrofit.create(RequestInterface.class);
Call<JSONResponse> call = request.getJSON();
final ProgressDialog progressDialog = new ProgressDialog(getActivity());
progressDialog.show();
call.enqueue(new Callback<JSONResponse>() {
#Override
public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {
progressDialog.dismiss();
JSONResponse jsonResponse = response.body();
data.addAll(Arrays.asList(jsonResponse.getAndroid()));
adapter.notifyDataSetChanged();
}
#Override
public void onFailure(Call<JSONResponse> call, Throwable t) {
progressDialog.dismiss();
Log.d("Error", t.getMessage());
}
});
}
else {
Toast.makeText(getActivity().getApplicationContext(), "Internet is disconnected", Toast.LENGTH_LONG).show();}
}
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni == null) {
// There are no active networks.
return false;
} else
return true;
}
}
RequestInterface :
public interface RequestInterface {
#GET("Erfan/news.php")
Call<JSONResponse> getJSON();
}
UPDATE (read below text and find your problem)
most of the time, this error isn't about your json but it could be a
incorrect http request such as a missing or a incorrect header, first check your request with postman to verify the servers response and servers response headers. if nothing is wrong then the error mostly came from your programmed http request, also it could because the servers response is not json (in some cases response could be html).
This is a well-known issue and based on this answer you could add setLenient:
Gson gson = new GsonBuilder()
.setLenient()
.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
Now, if you add this to your retrofit, it gives you another error:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $
This is another well-known error you can find answer here (this error means that your server response is not well-formatted); So change server response to return something:
{
android:[
{ ver:"1.5", name:"Cupcace", api:"Api Level 3" }
...
]
}
For better comprehension, compare your response with Github api.
Suggestion: to find out what's going on with your request/response add HttpLoggingInterceptor in your retrofit.
Based on this answer your ServiceHelper would be:
private ServiceHelper() {
httpClient = new OkHttpClient.Builder();
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
httpClient.interceptors().add(interceptor);
Retrofit retrofit = createAdapter().build();
service = retrofit.create(IService.class);
}
Also don't forget to add:
compile 'com.squareup.okhttp3:logging-interceptor:3.3.1'
Using Moshi:
When building your Retrofit Service add .asLenient() to your MoshiConverterFactory. You don't need a ScalarsConverter. It should look something like this:
return Retrofit.Builder()
.client(okHttpClient)
.baseUrl(ENDPOINT)
.addConverterFactory(MoshiConverterFactory.create().asLenient())
.build()
.create(UserService::class.java)
Also this issue occurres when the response contenttype is not application/json. In my case response contenttype was text/html and i faced this problem. I changed it to application/json then it worked.
There was an error in understanding of return Type
Just add Header and it will solve your problem
#Headers("Content-Type: application/json")
I had same issue along with https://stackoverflow.com/a/57245058/8968137 and both solved after fixing the google-services.json
Im my case I forgot add #Headers("Accept: application/json") to Retrofit and have redirect on http page, with html in body razer json
I have faced this problem and I made research and didn't get anything, so I was trying and finally, I knew the cause of this problem.
the problem on the API, make sure you have a good variable name
I used $start_date and it caused the problem, so I try $startdate and it works!
as well make sure you send all parameter that declare on API, for example,
$startdate = $_POST['startdate'];
$enddate = $_POST['enddate'];
you have to pass this two variable from the retrofit.
as well if you use date on SQL statement, try to put it inside ''
like '2017-07-24'
I hope it helps you.
In my case ; what solved my issue was.....
You may had json like this, the keys without " double quotations....
{ name: "test", phone: "2324234" }
So try any online Json Validator to make sure you have right syntax...
Json Validator Online
I solved this problem very easily after finding out this happens when you aren't outputting a proper JSON object, I simply used the echo json_encode($arrayName); instead of print_r($arrayName); With my php api.
Every programming language or at least most programming languages should have their own version of the json_encode() and json_decode() functions.
This issue started occurring for me all of a sudden, so I was sure, there could be some other reason. On digging deep, it was a simple issue where I used http in the BaseUrl of Retrofit instead of https. So changing it to https solved the issue for me.
Also worth checking is if there are any errors in the return type of your interface methods. I could reproduce this issue by having an unintended return type like Call<Call<ResponseBody>>
Sometimes the error is displayed because the Relative link cannot find the data in the Base URL;
I experienced the same issue and counterchecking that there is no error between the relative URL and base URL worked
I solve this issue after spending around 3 hrs. I have used postman for Api testing.
there was mistake in json output. Please see images for more clarification (I got this error when output preview change from enter image description here JSON to HTML)

Add Response call back when using retrofit with rxjava

I am using retrofit with Rxjava to get response from API as you can see the method i am using i can't see what's coming in the response and offcourse i don't need to becuase i am providing GsonConverter to retrofit but for some debugging reason i need to see the response that coming from API. How can i do this, what code i need to add.
public interface ProductApiService
{
String END_POINT = "http://beta.site.com/index.php/restmob/";
#GET(Url.URL_PRODUCT_API)
Observable<Product> getProducts(#Query("some_id") String cid);
class Creator
{
public static ProductApiService getProductAPIService() {
Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ProductApiService.END_POINT)
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
return retrofit.create(ProductApiService.class);
}
}
}
You can only do this as of Retrofit 2: Change the return type to include Response:
#GET(Url.URL_PRODUCT_API)
Observable<Response<Product>> getProducts(/* ...etc... */);
You can also use Observable<Result<Product>> if you want to see all possible errors in onNext (including IOException, which normally uses onError).
Daniel Lew's approach is quick and contains the least amount of boiler plate code. However, this may force you to refactor your networking logic. Since you mention needing this for debugging purposes, perhaps using a configured OkHttpClient with Interceptors is a less intrusive strategy.
OkHttpClient httpClient = new OkHttpClient.Builder()
.addInterceptor(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Request req = chain.request();
Response resp = chain.proceed(req);
// ... do something with response
return resp;
}
})
.build();
Retrofit retrofit = new Retrofit.Builder()
.client(httpClient)
.baseUrl(ProductApiService.END_POINT)
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();

Can someone explain to me if this is a singleton object? (Android)

i'm still new with singletons. I'm trying to use the DRY methode, but i'm not sure if it's correct. Below you find the class Authorization which i use to create a OkHttpClient and Retrofit.Builder. I'm not sure if it's the right way:
public class Authorization {
private static Retrofit retrofit = null;
public static Retrofit authorize(Activity activity){
final String token = SharedPreferencesMethods.getFromSharedPreferences(activity, activity.getString(R.string.token));
OkHttpClient client = new OkHttpClient();
client.interceptors().add(new Interceptor() {
#Override
public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
Request newRequest =
chain.request().newBuilder()
.addHeader("Authorization", "Bearer " + token).build();
return chain.proceed(newRequest);
}
});
if(retrofit == null){
retrofit = new Retrofit.Builder()
//10.0.3.2 for localhost
.baseUrl("http://teamh-spring.herokuapp.com")
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
The return value of the method authorize is returning a retrofit object.
Is it a singleton?
Here i call the api
CirkelsessieAPI cirkelsessieAPI = Authorization.authorize(getActivity()).create(CirkelsessieAPI.class);
Call<List<Cirkelsessie>> call = cirkelsessieAPI.getCirkelsessies();
// more code here
Thank you!
No it's not. A singleton is a design pattern that restricts the instanciation of a class to one object. I'm sure you can see why you can instantiate more than one Authorization object, and while the class "Authorization" restricts the instanciation of the class Retrofit to one object for its attribute, it can't in any way restricts someone else from instantiating another Retrofit object somewhere else.

Categories

Resources