Android Studio - Using retrofit2 to get info from restdb - android

I'm trying to use Retrofit2 to create a GET petition for my Android app. I have followed a tutorial on how to create the code and it worked with a webpage that did not need any authentication. Then I tried to adapt the same code to my needs, but I can't get it right. Either I get a 401 error or I get a 500 error.
I want to reach this URL: http://adaptai-eea8.restdb.io/rest/usuarios
So my baseurl is http://adaptai-eea8.restdb.io/.
This is my function, which is in the MainActivity:
private void find(String codigo){
String apikey = "9dc3afb8b6087192d5e9e50c5f2cb44927be5";
Retrofit retrofit = new Retrofit.Builder().baseUrl("http://adaptai-eea8.restdb.io/")
.addConverterFactory(GsonConverterFactory.create()).build();
UsuarioAPI usuarioAPI = retrofit.create(UsuarioAPI.class);
Call<Usuario> call = usuarioAPI.find(codigo);
call.enqueue(new Callback<Usuario>() {
#Override
public void onResponse(Call<Usuario> call, Response<Usuario> response) {
try {
int a = 5;
if(response.isSuccessful()){
Usuario u = response.body();
textView.setText(u.getContra());
Log.d("Funciona", u.getContra());
}
}catch(Exception ex){
Toast.makeText(MainActivity.this, ex.getMessage(), Toast.LENGTH_SHORT);
}
}
#Override
public void onFailure(Call<Usuario> call, Throwable t) {
Toast.makeText(MainActivity.this, "Error de conexión", Toast.LENGTH_SHORT);
}
});
}
And this is the GET petition I am using:
#Headers({"User-Agent: my-restdb-app","Content-Type: application/x-www-form-urlencoded", "x-apikey: heregoestheapikey", "Accept: application/json", "cache-control: no-cache"})
//#FormUrlEncoded
#GET("rest/usuarios/")
//public Call<Usuario> find(#Query("nombre") String nombre);
Call<Usuario> find(#Query("nombre") String nombre);
There has to be something wrong with this code, and maybe it is related to sending the apikey as a header, i don't know. Can someone tell me where am I wrong? Thanks in advance.

If you want to pass the apiKey as header you need to pass it as a parameter like you can see in the docs
#Headers({"User-Agent: my-restdb-app","Content-Type: application/x-www-form-urlencoded", "Accept: application/json", "cache-control: no-cache"})
#GET("rest/usuarios/")
Call<Usuario> find(#Header("x-apikey") String apiKey, #Query("nombre") String nombre);
Additionally, are you sure about the rest of parameters? Like User-Agent being "my-restdb-app" and query param name being "nombre"

Related

Retrofit call returning 400, cURL request working perfectly fine, syntax issue

I've tried making a retrofit call to an API endpoint, but it's returning a 400 error, however my curl request is working perfectly fine. I can't seem to spot the error, could someone double check my work to see where I made a mistake?
The curl call that works:
curl --request POST https://connect.squareupsandbox.com/v2/payments \
--header "Content-Type: application/json" \
--header "Authorization: Bearer accesstoken112233" \
--header "Accept: application/json" \
--data '{
"idempotency_key": "ab2a118d-53e2-47c6-88e2-8c48cb09bf9b",
"amount_money": {
"amount": 100,
"currency": "USD"},
"source_id": "cnon:CBASEITjGLBON1y5od2lsdxSPxQ"}'
My Retrofit call:
public interface IMakePayment {
#Headers({
"Accept: application/json",
"Content-Type: application/json",
"Authorization: Bearer accesstoken112233"
})
#POST(".")
Call<Void> listRepos(#Body DataDto dataDto);
}
DataDto class:
public class DataDto {
private String idempotency_key;
private String amount_money;
private String source_id;
public DataDto(String idempotency_key, String amount_money, String source_id) {
this.idempotency_key = idempotency_key;
this.amount_money = amount_money;
this.source_id = source_id;
}
}
And lastly making the retrofit call:
DataDto dataDto = new DataDto("ab2a118d-53e2-47c6-88e2-8c48cb09bf9b", "{\"amount\": 100, \"currency\": \"USD\"}", "cnon:CBASEITjGLBON1y5od2lsdxSPxQ");
RetrofitInterfaces.IMakePayment service = RetrofitClientInstance.getRetrofitInstance().create(RetrofitInterfaces.IMakePayment.class);
Call<Void> call = service.listRepos(dataDto);
call.enqueue(new Callback<Void>() {
#Override
public void onResponse(#NonNull Call<Void> call, #NonNull Response<Void> response) {
Log.d(TAG, "onResponse: " + response.toString());
}
#Override
public void onFailure(#NonNull Call<Void> call, #NonNull Throwable t) {
Log.d(TAG, "onFailure: Error: " + t);
}
});
Retrofit Instance:
public class RetrofitClientInstance {
private static Retrofit retrofit;
private static final String BASE_URL = "https://connect.squareupsandbox.com/v2/payments/";
public static Retrofit getRetrofitInstance() {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
Edit 1: Changing to second parameter to JSON Object
JSONObject jsonObject = new JSONObject();
try{
jsonObject.put("amount", 100);
jsonObject.put("currency", "USD");
}catch (Exception e){
Log.d(TAG, "onCreate: " + e);
}
DataDto dataDto = new DataDto("ab2a118d-53e2-47c6-88e2-8c48cb09bf9b", jsonObject, "cnon:CBASEITjGLBON1y5od2lsdxSPxQ");
First of all, let's see what 400 means
The HyperText Transfer Protocol (HTTP) 400 Bad Request response status
code indicates that the server cannot or will not process the request
due to something that is perceived to be a client error (e.g.,
malformed request syntax, invalid request message framing, or
deceptive request routing).
Now we are sure, the problem stands in our request (not server fault), most probably it is because you are trying to convert JSON in request (do not do this explicitly GSON will convert automatically)
Use interceptor to verify your outgoing network requests (Tell the result here)
you use #POST(".") which does not make sense, please understand BASE_URL is your server URL NOT MORE
The problem could be translating this post request
So a possible solution
Change base URL into "https://connect.squareupsandbox.com/"
Replace #POST(".") with #POST("v2/payments/")
PS. #NaveenNiraula mentioned right thing even though it did not help you, please follow his instruction, it is the correct way parsing data using GSON (make sure you include it and configure it correctly) converter
EDIT
I make it work (I eliminated 400 error code that is what you want as long as question title is concerned) partially which means I detect why 400 error was occurred and fixed it but unfortunately, I stuck the UNAUTHORIZED issue. The problem was relating to converting json and data type
data class DataDTO(
val idempotency_key: String,
val source_id: String,
val amount_money: MoneyAmount
)
data class MoneyAmount(
val amount: Int,
val currency: String
)
I gist all code here you can refer
You need two DTO classes as below:
public class Amount_money
{
private String amount;
private String currency;
public String getAmount ()
{
return amount;
}
public void setAmount (String amount)
{
this.amount = amount;
}
public String getCurrency ()
{
return currency;
}
public void setCurrency (String currency)
{
this.currency = currency;
}
#Override
public String toString()
{
return "ClassPojo [amount = "+amount+", currency = "+currency+"]";
}
}
And
public class DataDto
{
private String idempotency_key;
private Amount_money amount_money;
private String source_id;
public String getIdempotency_key ()
{
return idempotency_key;
}
public void setIdempotency_key (String idempotency_key)
{
this.idempotency_key = idempotency_key;
}
public Amount_money getAmount_money ()
{
return amount_money;
}
public void setAmount_money (Amount_money amount_money)
{
this.amount_money = amount_money;
}
public String getSource_id ()
{
return source_id;
}
public void setSource_id (String source_id)
{
this.source_id = source_id;
}
#Override
public String toString()
{
return "ClassPojo [idempotency_key = "+idempotency_key+", amount_money = "+amount_money+", source_id = "+source_id+"]";
}
}
You need to create object for each like under :
Amount_money am = new Amount_money();
am.setAmount("100");
am.setCurrency("USD");
DataDto dto = new DataDto();
dto.setIdempotency_key("your key");
dto.setsource_id("your id");
dto.setAmount_money(am);
RetrofitInterfaces.IMakePayment service = RetrofitClientInstance.getRetrofitInstance().create(RetrofitInterfaces.IMakePayment.class);
Call<Void> call = service.listRepos(dataDto);
// yo get the point follow along
Most likely the passed JSON structure is not serialized in the same format.
"amount_money": {
"amount": 100,
"currency": "USD"},
I would at first use for private String amount_money; a real DTO having the amount and currency fields. This should give progress. I'm not 100% sure how the underscore mapping of attributes looks like, but this is the next step.
Add logging to be able to see the passed data. A quick search reveals this tutorial: https://futurestud.io/tutorials/retrofit-2-log-requests-and-responses. When seeing the transmitted data it should be easy to compare the expected and sent data.
Please check your base url.
In your curl you have https://connect.squareupsandbox.com/v2/payments
But in the code you have
private static final String BASE_URL = "https://connect.squareupsandbox.com/v2/payments/";
There is extra / (slash) in the end. I've seen cases where it was the issue. Could be your problem :)

Instagram api - Retrofit2 - unable to do POST request

I am new to retrofit and I am trying to send a comment to a specific media using retrofit and the Instagram API.
The Instagram API tells me that my request must be:
curl -F 'access_token=ACCESS-TOKEN'
-F 'text=This+is+my+comment'
https://api.instagram.com/v1/media/{media-id}/comments
and the JSON response is :
{
"meta":
{
"code": 200
},
"data": null
}
So I made this retrofit grammar:
#FormUrlEncoded
#POST("v1/media/{media_id}/comments")
Call<Object> postComment(
#Path("media_id") String mediaId,
#Field("access_token") String accessToken,
#Field("text") String text);
My Retrofit Service:
public class RestClient
{
public static RetrofitInstagram getRetrofitService()
{
return new Retrofit.Builder()
.baseUrl(Constants.AUTH_URL)
.addConverterFactory(GsonConverterFactory.create())
.build().create(RetrofitInstagram.class);
}
}
My call (inside an AlertDialog get the text from an EditText) is :
Call<Object> call = RestClient.getRetrofitService().postComment(data.get(idx).getId(), access_token, titleEditText.getText().toString());
call.enqueue(new Callback<Object>()
{
#Override
public void onResponse(Call<Object> call, Response<Object> response)
{
Log.d("response comment", ""+response.raw());
Toast.makeText(activity_instagram_feed_search.this, "Comments sent", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<Object> call, Throwable t)
{
Toast.makeText(activity_instagram_feed_search.this, "error", Toast.LENGTH_SHORT).show();
}
});
My problem here is that I am receiving a code 400 error (Missing client_id or access_token URL parameter.).
It's like the api think I am doing a GET request.
I am really confuse, I would appreciate some wisdom :).
I managed to find the solution to my question.
So Ben P was wrong and the Curl -F is x-www-form-urlencoded.
I am in sandbox account mode and forgot to add comments scope to my loggin
WebView request.
So my WebView url is now:
private final String url = Constants.AUTH_URL
+ "oauth/authorize/?client_id="
+ Constants.CLIENT_ID
+ "&redirect_uri="
+ Constants.REDIRECT_URI
+ "&response_type=token"
+ "&display=touch&scope=public_content+comments";

How to get simple JSON object in Retrofit 2.0.0 beta 1?

I am trying to convert this simple response that looks like this
{
"field_one": "bearer",
"field_two": "fgh",
"field_three": 0
}
I am using latest version of Retrofit 2.0.0-beta1. I never used Retrofit before. There are many tutorials and example of old version of Retrofit. I tried different techniques that works with older versions but thats not working with latest one. Due to lack of documentation of latest version of Retrofit I could not find solution.
I want to use latest version.
Here is POJO
public class Auth {
#SerializedName("field_one")
#Expose
private String fieldOne;
#SerializedName("field_two")
#Expose
private String fieldTwo;
#SerializedName("field_three")
#Expose
private Integer fieldThree;
// setter and getter etc. etc.
}
Here is Interface that I am using
interface Authorization {
#Headers("Authorization: This is some header")
#GET("api/v1/mytoken")
Call<Auth> getToken();
}
This is the way I am calling service
OkHttpClient client = new OkHttpClient();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://myendpoint.com/")
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
Authorization serviceAuthorization = retrofit.create(Authorization.class);
serviceAuthorization.getToken().enqueue(new Callback<Auth>() {
#Override
public void onResponse(Response<Auth> response) {
Log.d("Response", ">>> "+ response.toString());
}
#Override
public void onFailure(Throwable t) {
Log.d("fail", ">>> "+ t.getMessage());
}
});
I am unable to get output. It just print this
Response: >>> retrofit.Response#2567e2c3
I want to get data in Auth Object that I will use later.
Please suggest me best solution
Thanks!
I guess that you are not seeing you are expecting to see your object printed out on this line --
Log.d("Response", ">>> "+ response.toString());
That is going to call the toString method on the response. If you want to call it on your deserialized object, call the body() method first --
if(response.isSuccess()) {
Log.d("Response", ">>> "+ response.body().toString());
} else {
Log.d("Response", "Error - " + response.code())
}

How to stream real time data using Retrofit

I want to observer changes from server in my android app.
So I'm using this interface for open stream with server.
public interface Service {
#GET("/n/{id}/streaming")
void streamThreads(#Path("name_space_id") String Id, #QueryMap Map<String, String> options,#Query("exclude_types") String type, Callback<Object> callback);
}
and this is my method where I can get response in my activity
server.streamThreads(accountInfo.getId(), map, "thread", new Callback<Object>() {
#Override
public void success(Object o, Response response) {
String json = (String) o;
Log.i(TAG,json);
}
#Override
public void failure(RetrofitError error) {
Response r = error.getResponse();
if (r != null)
Log.e(TAG, "error: " + r.getReason());
}
});
So I tested method in web browser and life stream works.
But response comes in my mobile app every 30 minutes. I'm using one activity and call method onCreate().
Thanks
Retrofit provides an #Streaming annotation.
The unread byteStream can then be obtained from the raw OkHttp ResponseBody.

Retrofit login using POST android

I'm trying to use the login API from my server via Retrofit but seems that I cannot make this right. Right now I'm getting this in logCat No Retrofit annotation found. (parameter #1) for using this code:
Api call:
http://www.myapi.com/v1/index.php/login with the parameters email and password
//this is the interface:
#POST("/login")
void login( String email,String password, Callback<BaseMO> callback);
//this is the api call
restAdapter = new RestAdapter.Builder()
.setEndpoint(ServerParams.API_URL)
.build();
ServerEndpoints apiService =
restAdapter.create(ServerEndpoints.class);
apiService.login("meil#gmail.com", "000000", new Callback<BaseMO>() {
#Override
public void success(BaseMO baseMO, Response response) {
Log.d(TAG, "Success " + response.getReason() + " | " + baseMO.getMessage());
}
#Override
public void failure(RetrofitError error) {
Log.d(TAG, "Error " + error.getMessage());
}
});
Can someone help me make this right. Thanks!
After a more carefull reading of the docs I've found my answer, I'll post it here so if someone in the future has this or similar problem.
The interface should be defined as:
#FormUrlEncoded
#POST("/login")
void login(#Field("email") String email,#Field("password")String password, Callback<BaseMO> callback);

Categories

Resources