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



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

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

这是我的改造服务类

公共类服务生成器 {

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);
}

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

public class HeadersInterceptor 实现 Interceptor {

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);
}

}

这是我的片段,它进行搜索查询并成功返回结果[接收ID]

公共类 ListSelectedFragments 扩展 Fragment {

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 Requestn"+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()  Calledn");
Log.d(TAG,"Response = "+ response);
if(response.body()!=null) {
String obj = response.body().getSourceUrl();
Log.d(TAG,"Getting Recipe Infon");
Log.d(TAG, String.valueOf(obj));
}
}
@Override
public void onFailure(@NonNull Call<RecipeDetailedInfo> call, @NonNull Throwable t){
}
});
}

使用邮递员,我每次都会得到结果,但在我的应用程序中,API 在第一次请求后停止响应。我包含标题的方式有问题吗?

所以我终于把事情搞定了。问题出在 HeadersInterceptor.java。我正在使用拦截器在调用中添加标头,但我发现了一种更简单的方法,它就像一个魅力。

只需在调用中添加@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);
}

最新更新