I've just get the code from response, and it says, that my request parameters are wrong, what should my api call look like then?
Here's the hardcoded api call from documenatation
https://api.themoviedb.org/3/discover/movie?api_key=[API_KEY]&with_genres=27
Here's my api call
#GET("3/search/movie")
Call<itemList_model> test(#Query("api_key") String key,#Query("with_genres") int query);
Code
Invalid parameters: Your request parameters are incorrect.
Retrofit call
public void getListViewItems() {
String url = "https://api.themoviedb.org/";
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
apiCall api = retrofit.create(apiCall.class);
Call<itemList_model> call = api.test("API_KEY",27); <- 27 stand's for horror genres.
call.enqueue(new Callback<itemList_model>() {
#Override
public void onResponse(Call<itemList_model> call, Response<itemList_model> response) {
if (!response.isSuccessful()) {
Log.i(TAG, "onResponse: " + response.code());
}
Log.i(TAG, "onResponse: "+response.code());
}
#Override
public void onFailure(Call<itemList_model> call, Throwable t) {
Log.i(TAG, "onFailure: " + t.getMessage());
}
});
}
Simple typo. Should be:
https://api.themoviedb.org/3/discover/movie?api_key=[API_KEY]&with_genres=27
But:
https://api.themoviedb.org/3/search/movie?api_key=[API_KEY]&with_genres=27
Working code
package test;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;
public interface RetrofitProxy {
#GET("3/discover/movie")
Call<Object> test(#Query("api_key") String apiKey, #Query("with_genres") int genreCode);
}
package test;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import java.io.IOException;
public class RetrofitTest {
public static void main(String[] args) throws IOException {
String url = "https://api.themoviedb.org/";
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
RetrofitProxy retrofitProxy = retrofit.create(RetrofitProxy.class);
Call<Object> call = retrofitProxy.test("API_KEY", 27);
Response<Object> execute = call.execute();
System.out.println(execute.raw());
System.out.println(execute.isSuccessful());
System.out.println(execute.body());
}
}
Related
I wanted to load a json, one after one, beacause its large JsonArray. before then i used Retrofit call and Its oKey, but the output take too long. Any help on how to implement it this way is appreciated.
ApiInterface.java
public interface ApiInterface {
#POST("/token/login")
Call<User> login(#Body Login login);
#Streaming
#GET("/api/schools/")
Observable<ResponseBody> getAllSchools(#Header("Authorization") String authToken);
}
Client.java
public class Client {
public static final String BASE_URL = "site.net";
private static Retrofit retrofit;
public static Retrofit getClient(){
if (retrofit == null){
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
}
return retrofit;
}
}
ApiInterface apiInterface = Client.getClient().create(ApiInterface.class);
String tok = "Token " + token;
apiInterface.getAllSchools(tok)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<ResponseBody>() {
#Override
public void onSubscribe(Disposable disposable) {
}
#Override
public void onNext(ResponseBody responseBody) {
//fetch json one after one.
Toast.makeText(getContext(), responseBody.toString(), Toast.LENGTH_SHORT).show();
}
#Override
public void onError(Throwable throwable) {
}
#Override
public void onComplete() {
Toast.makeText(getContext(), "finish--", Toast.LENGTH_SHORT).show();
}
});
so I coded this class to Download URLs but it's returning Null Response
I tried to debug but didn't understand anything
package com.example.instaup;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class Downloader
{
private String myResponse;
public String DownloadText(String url)
{
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(#NotNull Call call, #NotNull IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(#NotNull Call call, #NotNull Response response) throws IOException {
if (response.isSuccessful()) {
myResponse = response.body().toString();
}
}
});
return myResponse;
}
}
Can Someone Help me? I'm kinda new to this
You should reuse the client, and use the synchronous form execute instead of the enqueue callback API which returns almost immediately before the request has finished.
import java.io.IOException;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class Downloader {
OkHttpClient client = new OkHttpClient();
public String DownloadText(String url) throws IOException {
Request request = new Request.Builder().url(url).build();
try (Response myResponse = client.newCall(request).execute()) {
return myResponse.body().string();
}
}
}
i can't get the Key (token) by post method when i run the app it shows me an error (500) and the response is null,i tried many times but couldn't find the normal solution.
To be clear i am putting the Hometask and code below:
So the Hometask is :
Create one page Authorization, where there are two fields - Partner Login and Password
Partner account for your testing:
Login: login
Password: password
1) Authorization:
http://client-api.instaforex.com/Home/GetAPIUsageInfo
You need to get token "RequestMoblieCabinetApiToken".
Request URL: http://client-api.instaforex.com/api/Authentication/RequestMoblieCabinetApiToken
Method: POST
Request:
{
"Login": "PARTNER_LOGIN",
"Password": "PARTNER_PASSWORD"
}
In response you get "passkey" (your token).
My code:
ApiInterface
package com.example.instaforexapp.Rest;
import com.example.instaforexapp.Modal.ApiAccount;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;
public interface InstaForexApi {
#FormUrlEncoded
#POST("api/Authentication/RequestMoblieCabinetApiToken")
Call<ApiAccount> createAccount( #Field("Login") String login,
#Field("Password") String password);
}
ApiClient
package com.example.instaforexapp.Rest;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class ApiClient {
private static final String BASE_URL = "http://client-api.instaforex.com/";
private static Retrofit retrofit = null;
public static Retrofit getRetrofit() {
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
httpLoggingInterceptor.level(HttpLoggingInterceptor.Level.BODY);
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addInterceptor(httpLoggingInterceptor)
.build();
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.build();
}
return retrofit;
}
}
ApiAccount Class
import com.google.gson.annotations.SerializedName;
public class ApiAccount {
#SerializedName("Login")
private String login;
#SerializedName("Password")
private String password;
public ApiAccount(String login, String password) {
this.login = login;
this.password = password;
}
public String getLogin() {
return login;
}
public String getPassword() {
return password;
}
}
MainActivity
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.instaforexapp.Modal.ApiAccount;
import com.example.instaforexapp.Rest.ApiClient;
import com.example.instaforexapp.Rest.InstaForexApi;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class MainActivity extends AppCompatActivity {
private EditText txt_login,txt_password;
private Button btn_confirm;
public static final String TAG = "com.MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt_login = findViewById(R.id.txt_login);
txt_password = findViewById(R.id.txt_pass);
btn_confirm = findViewById(R.id.btn_confirm);
btn_confirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String login = txt_login.getText().toString();
String password= txt_password.getText().toString();
createAccount(login,password);
Log.i(TAG, "login :"+login +" password: "+password);
}
});
}
private void createAccount(String login,String password){
InstaForexApi api = ApiClient.getRetrofit().create(InstaForexApi.class);
Call<ApiAccount> call = api.createAccount(login,password);
call.enqueue(new Callback<ApiAccount>() {
#Override
public void onResponse( Call<ApiAccount> call, Response<ApiAccount> response) {
if (!response.isSuccessful()){
Toast.makeText(MainActivity.this, "Error: "+response.code(),
Toast.LENGTH_SHORT).show();
}
ApiAccount account = response.body();
String toast = null;
if (account != null) {
toast = account.getLogin()+" : " + account.getPassword();
}
Toast.makeText(MainActivity.this, toast, Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<ApiAccount> call, Throwable t) {
Toast.makeText(MainActivity.this, t.getMessage(),
Toast.LENGTH_SHORT).show();
}
});
}
}
Please help to get the "passkey"
500 status code from server means that your server isn't available at the moment now this issues is not at your end so better communicate with your backend team to resolve this. Check this link to understand about status codes better in server response
My interface
#POST("/insert.php")
void login(Callback<Response> callback);
Java code
Retrofit adapter = new Retrofit.Builder()
.baseUrl(ROOT_URL) //Setting the Root URL
.addConverterFactory(GsonConverterFactory.create())
.build(); //Finally building the adapter
Register_Retrofit api = adapter.create(Register_Retrofit.class);
api.login( new Callback<Response>() {
public void onResponse(Call<Response> call, Response<Response> response) {
}
public void onFailure(Call<Response> call, Throwable t) {
}
});
Your login method return void, so you need to define it like this:
#POST("/insert.php")
Call<Void> login();
Then, to call the login method try this:
Retrofit adapter = new Retrofit.Builder()
.baseUrl(ROOT_URL) //Setting the Root URL
.addConverterFactory(GsonConverterFactory.create())
.build(); //Finally building the adapter
Register_Retrofit api = adapter.create(Register_Retrofit.class);
Call<Void> loginCall = api.login();
loginCall.enqueue(new Callback<Void>() {
public void onResponse(Call<Void> call, Response<Void> response) {
...
}
public void onFailure(Call<Void> call, Throwable t) {
...
}
});
I know that with application.yml I can modify the url that call a microservice but my doubt is how can I implement zuul with hystrix circuit braker?, I have a class that extends ZuulFilter and in my run method I'm trying to execute the hystrixCommand like this:
#Override
public Object run() {
RequestContext ctx = RequestContext.getCurrentContext();
HttpServletRequest request = ctx.getRequest();
HystrixCommand<String> hystrixCommand = new HystrixCommand<String>(HystrixCommandGroupKey.Factory.asKey(request.getRequestURL().toString())) {
#Override
protected String run() throws Exception {
RestTemplate restTemplate = new RestTemplate();
String responseBody = restTemplate.getForObject(request.getRequestURL().toString(), String.class);
return responseBody;
}
#Override
protected String getFallback() {
return "No response from server";
}
};
String response = hystrixCommand.execute();
RequestContext.getCurrentContext().setResponseBody(response);
return null;
}
But how can I tell hystrixCommand to use the getFallback method if the actual URL failed?, I thought to call the same URL but I think if I do that it will do an infinite cycle or am I not understanding?
Thanks in advance.
UPDATE
This is my whole filter class
package com.filter;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import javax.servlet.http.HttpServletRequest;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.springframework.web.client.RestTemplate;
public class ZuulHttpFilter extends ZuulFilter{
#Override
public String filterType() {
return "pre";
}
#Override
public int filterOrder() {
return 10000;
}
#Override
public boolean shouldFilter() {
return true;
}
#Override
public Object run() {
RequestContext ctx = RequestContext.getCurrentContext();
HttpServletRequest request = ctx.getRequest();
HystrixCommand<String> hystrixCommand = new HystrixCommand<String>(HystrixCommandGroupKey.Factory.asKey(request.getRequestURL().toString())) {
#Override
protected String run() throws Exception {
RestTemplate restTemplate = new RestTemplate();
String responseBody = restTemplate.getForObject(request.getRequestURL().toString(), String.class);
return responseBody;
}
#Override
protected String getFallback() {
return "No response from server";
}
};
String response = hystrixCommand.execute();
RequestContext.getCurrentContext().setResponseBody(response);
return null;
}
}
Did you see this question? In fact, the Hystrix javadoc says that it is supposed to execute the fallback automatically:
Returns: R Result of run() execution or a fallback from getFallback()
if the command fails for any reason.