Retrofit 2 removes posrt after special character ":" from base Url - android

I have an Api https://hello.example.com:344/new/search/result.
Implementing same using Retrofit 2:
This is how initialising retrofit:
public static void initializeRetrofit() {
Retrofit retrofit = new Retrofit.Builder().baseUrl("https://hello.example.com:344")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
service2 = retrofit.create(ContentService.class);
}
This is the interface request:
#POST("new/search/result")
Call<JsonObject> getSearchList(#Body JsonObject request);
But when i hit api : it removes the port from it and hits
"https://hello.example.com/new/search/result"
What is going wrong?

In your base url "https://hello.example.com:344" transform it to
"https://hello.example.com:344/"

There is no / (slash) in your base url as well as in the interface function. So the request becomes like "https://hello.example.com:344new/search/result " which will give u an error.
Add slash at the end of your base url like this "https://hello.example.com:344/"

Related

Retrofit pass parameter through post and get result

This is my Api.php
$command=$_POST["command"];
if($command=="getUsers"){
getUsers();
}
elseif ($command=="getNews")
{
getNews();
}
I'm using retrofit to show result in my android app. I need to pass parameter Command through Retrofit Post and Get a result at the same time.
what's the solution?
Try like this example from Retrofit website:
#FormUrlEncoded
#POST("user/edit")
Call<User> updateUser(#Field("first_name") String first, #Field("last_name") String last);
Source: https://square.github.io/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.

Is there a way to get passed in post request parameters during building process in Retrofit2.1.0?

I am trying to compute a checksum from HTTP arguments dynamically. And then I would like to add this checksum as an HTTP argument.
I need to get the fields that are passed in as parameters first, but it looks like retrofit can only access url query parameters.
#Gordak shows the way to get query parameter, but what I want to achive, if any possible, to get post parameters in the request chain.
Okay, here we go.
First, build your OkHTTP client and retrofit object.
OkHttpClient client = httpBuilder
.addNetworkInterceptor(INTERCEPTOR_REQUEST_ADD_CHECKSUM)
.build();
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.baseUrl("https://my.domain.com")
.build();
Then, you need to define your interceptor :
private static final Interceptor INTERCEPTOR_REQUEST_ADD_CHECKSUM = new Interceptor() {
#Override
public Response intercept(Interceptor.Chain chain) throws IOException {
HttpUrl url = chain.request().url();
String param1 = url.queryParameter("param1");
String param2 = url.queryParameter("param2");
String chk = aMethodToComputeChecksum(param1,param2);
url = url.newBuilder().addQueryParameter("checksum", chk).build();
Request request = chain.request().newBuilder().url(url).build();
return chain.proceed(request);
}
Maybe it will help - try to compute this parameter once and write it in RequestInterceptor

How to make Java REST API GET Request using Retrofit2.0?

I'm using Retrofit2.0 for making GET request to my REST URL. I don't need to pass any params to url for making the request.
How could on can make this type of request?
Here is my code what i 've done!
Interface ::
public interface AllRolesAPI {
#GET("/SportsApp/allroles")
Call<AllRolesParams> getAllRoles();
}
Class :::
I created a class using Pojo library it contains all the variables with setter and getter methods.
public void requestRoles() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ENDPOINT)
.build();
AllRolesAPI allRolesParams = retrofit.create(AllRolesAPI.class);
Call<AllRolesParams> allRolesParamsCall = allRolesParams.getAllRoles();
allRolesParamsCall.enqueue(new Callback<AllRolesParams>() {
#Override
public void onResponse(Call<AllRolesParams> call, Response<AllRolesParams> response) {
//response.body().getErrDesc();
Log.v("SignupActivity", "Response :: " + response.body().getErrDesc());
}
#Override
public void onFailure(Call<AllRolesParams> call, Throwable t) {
Log.v("SignupActivity", "Failure :: ");
}
});
}
When I create a request like above I have got this error in console ::
java.lang.IllegalArgumentException: Unable to create converter for class com.acknotech.kiran.navigationdrawer.AllRolesParams.
If your API's responses are JSON, you need to add
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ENDPOINT)
.addConverterFactory(GsonConverterFactory.create())
.build();
In order to be able to use GsonConverterFactory, you need to add a gradle dependency. Check this. In your case is
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
(2.1.0 is the latest version at the time of this writing)
Quoting official docs:
By default, Retrofit can only deserialize HTTP bodies into OkHttp's
ResponseBody type and it can only accept its RequestBody type for
#Body. Converters can be added to support other types. Six sibling
modules adapt popular serialization libraries for your convenience.
Gson: com.squareup.retrofit2:converter-gson
Jackson:com.squareup.retrofit2:converter-jackson
Moshi:com.squareup.retrofit2:converter-moshi
Protobuf:com.squareup.retrofit2:converter-protobuf
Wire:com.squareup.retrofit2:converter-wire
Simple XML:com.squareup.retrofit2:converter-simplexml
Scalars (primitives, boxed,and String): com.squareup.retrofit2:converter-scalars
You are trying to parse JSON without any converter. There are various converts you can use with Retrofit. Most Popular is Gson Converter from Google. To make your code work create Retrofit adapter like this:
adapter = new Retrofit.Builder() //in your case replace adapter with Retrofit retrofit
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
Also make sure to include these dependencies:
compile 'com.google.code.gson:gson:2.6.2'
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
Hope it works.You can refer to official retrofit docs,this guide and gson guide for more information.

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

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***");

Categories

Resources