带有Retrofit2 Android的快速API错误代码500

时间:2019-06-21 17:27:01

标签: android retrofit2 internal-server-error http-status-code-500

我在食谱应用程序项目中使用了勺形API。尝试向API发出多个GET请求时,会发生此问题。第一个请求是带有查询参数的简单搜索。第一个请求的结果JSON包含一个配方ID,我使用该ID进行第二个GET请求,在此发生问题。 该API仅在我第一次发出请求时才响应,但之后会以错误代码500 [内部服务器错误]响应。

我已经在Postman上测试了GET请求,但是每次都可以正常工作。 我是使用API​​的新手,我们将不胜感激任何帮助。

这是我的翻新服务课程

公共类ServiceGenerator {

public static final String API_BASE_URL = "https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com/";

private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

private static Retrofit.Builder builder =
        new Retrofit.Builder()
                .baseUrl(API_BASE_URL)
                .addConverterFactory(GsonConverterFactory.create());

private static Retrofit retrofit = builder.build();

public static <S> S createService(Class<S> serviceClass, final String HostName, final String KeyVal)
{
    if (!TextUtils.isEmpty(HostName) && !TextUtils.isEmpty(KeyVal))
    {
        HeadersInterceptor interceptor = new HeadersInterceptor(HostName,KeyVal);

        if (!httpClient.interceptors().contains(interceptor))
        {
            httpClient.addInterceptor(interceptor);
            builder.client(httpClient.build());
            retrofit = builder.build();
        }
    }

    return retrofit.create(serviceClass);
}

这是我用来向请求添加标头的拦截器。

公共类HeadersInterceptor实现了拦截器{

private String HostName,KeyVal;

HeadersInterceptor(final String HostName,final String KeyVal) {
    this.HostName = HostName;
    this.KeyVal = KeyVal;
}

@NotNull
@Override
public Response intercept(@NotNull Chain chain) throws IOException {
    Request original = chain.request();

    Request.Builder builder = original.newBuilder()
            .addHeader("X-RapidAPI-Host",HostName)
            .addHeader("X-RapidAPI-Key",KeyVal);

    Request request = builder.build();
    return chain.proceed(request);
}

}

这是我的片段,它进行搜索查询并成功返回结果[Receipe ID's

公共类ListSelectedFragments扩展了片段{

private ProgressBar PreviewFragPrg;
private final String TAG = "ListSelectedFragment->";

private PreviewRecipeAdapter adapter;
private RecyclerView SelectedItemRV;
private ArrayList<RecipePreviewHolder> RecipePreviewsList = new ArrayList<>();

public ListSelectedFragments() {
    // Required empty public constructor
}


@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    final View view = inflater.inflate(R.layout.fragment_list_selected_fragments, container, false);
    SelectedItemRV = view.findViewById(R.id.SelectedItemRV);
    TextView DisplayNameTV = view.findViewById(R.id.DisplayNameTV);
    PreviewFragPrg = view.findViewById(R.id.PreviewFragPrg);
    ImageView BackBtn = view.findViewById(R.id.BackBtn);

    BackBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (getFragmentManager() != null) {
                getFragmentManager().popBackStackImmediate();
            }
        }
    });

    if (getArguments() != null) {
        final String QueryTag = getArguments().getString("QueryTag");
        final String CuisineName = getArguments().getString("CuisineName");

        if(CuisineName!=null){
            DisplayNameTV.setText(CuisineName);
        }
        if(QueryTag!=null){
            ProcessQuery(QueryTag);
        }
    }

    return view;
}

private void ProcessQuery(final String QueryStr){

    String hostname = getResources().getString(R.string.spoonacular_host_name);
    String key      = getResources().getString(R.string.spoonacular_apikey_val);


    final ServiceGenerator.GetDataService mService =
            ServiceGenerator.createService(ServiceGenerator.GetDataService.class, hostname,key);

    Call<RecipeInfoModel> call = mService.getRecipes(QueryStr);

    call.enqueue(new Callback<RecipeInfoModel>() {
        @Override
        public void onResponse(@NonNull Call<RecipeInfoModel> call,
                               @NonNull Response<RecipeInfoModel> response)
        {
            Log.d(TAG, "Request Response Received");
            Log.d(TAG, response.toString());

            if (response.body() != null) {
                Results[] mRES = response.body().getResults();
                SetUpRecipePreviews(mRES);
                PreviewFragPrg.setVisibility(View.GONE);
            }
        }

        @Override
        public void onFailure(@NonNull Call<RecipeInfoModel> call, @NonNull Throwable t) {
            Log.d(TAG, "Request Failed");
            Log.d(TAG, call.toString());
            Log.d(TAG, "Throwable ->" + t);
            PreviewFragPrg.setVisibility(View.GONE);
            Toast.makeText(getActivity(),"Could not get required recipes",Toast.LENGTH_SHORT).show();
        }
    });

    Log.d(TAG, "User Inputed Request\n"+call.request().url().toString());

}

private void SetUpRecipePreviews(final Results[] mRES) {

    RecipePreviewsList.clear();
    adapter = new PreviewRecipeAdapter(getActivity(),RecipePreviewsList);
    SelectedItemRV.setLayoutManager(new GridLayoutManager(getActivity(), 2));
    SelectedItemRV.setAdapter(adapter);

    for (Results mRE : mRES) {
        String ImgUrls = mRE.getImage();
        RecipePreviewHolder obj = new RecipePreviewHolder(Integer.valueOf(mRE.getId()),
                mRE.getTitle(), ImgUrls);
        Log.d("GlideLogs->","Rid->"+mRE.getId());
        Log.d("GlideLogs->","Img URL->"+ ImgUrls);
        Log.d("GlideLogs->","Name->"+mRE.getTitle());

        RecipePreviewsList.add(obj);
    }

    if(RecipePreviewsList.size()>1){
        adapter.notifyDataSetChanged();
    }
}

这是我在单击食谱卡后从片段过渡到的活动...在其他内容中发送食谱ID。收到意向附加信息后立即调用此函数。

private void RetrieveRecipeInfo(final int recipeID){

    String hostname = getResources().getString(R.string.spoonacular_host_name);
    String key   = getResources().getString(R.string.spoonacular_apikey_val);


    final ServiceGenerator.GetDataService mService =
            ServiceGenerator.createService(ServiceGenerator.GetDataService.class, hostname,key);

    Call<RecipeDetailedInfo> call = mService.getInformation(185071);
    Log.d(TAG , "Your GET Request:\n"+call.request().url().toString());

    call.enqueue(new Callback<RecipeDetailedInfo>() {
        @Override
        public void onResponse(@NonNull Call<RecipeDetailedInfo> call, @NonNull Response<RecipeDetailedInfo> response)
        {
            Log.d(TAG,"OnResponse()  Called\n");
            Log.d(TAG,"Response = "+ response);

            if(response.body()!=null) {
                String obj = response.body().getSourceUrl();
                Log.d(TAG,"Getting Recipe Info\n");
                Log.d(TAG, String.valueOf(obj));
            }
        }

        @Override
        public void onFailure(@NonNull Call<RecipeDetailedInfo> call, @NonNull Throwable t){
        }
    });
}

我每次都使用邮递员获得结果,但是在我的应用程序中,API在第一个请求后停止响应。我添加标头的方式有问题吗?

1 个答案:

答案 0 :(得分:1)

所以我终于让事情开始了。问题出在HeadersInterceptor.java。我当时使用Interceptor在呼叫中添加了Headers,但是我发现了一种简单得多的方法,它就像一种魅力。

只需在调用中添加@Header,即可在Retrofit中添加不带拦截器的标头。

public interface GetDataService {
    @GET("recipes/complexSearch?")
    Call<RecipeInfoModel> getRecipes(
            @Header("X-RapidAPI-Host") String api,
            @Header("X-RapidAPI-Key") String apiKey,
            @Query("query") String query_str);
}