如何解决android studio中cowin公共api的错误代码403?

soat7uwm  于 2021-09-29  发布在  Java
关注(0)|答案(1)|浏览(488)

以下是cowin公共api的链接:
https://apisetu.gov.in/public/marketplace/api/cowin#/
https://cdn-api.co-vin.in/api/v2/admin/location/states
我一直在尝试使用改型库从android studio的第二个链接获取状态详细信息。但每次我运行应用程序时,它都会显示错误403。任何帮助都将不胜感激!!在下面添加我的代码:
关于创建活动:

  1. Retrofit retrofit = new Retrofit.Builder().baseUrl("https://cdn-api.co-vin.in/api/").addConverterFactory(GsonConverterFactory.create()).build();
  2. CovidAPI covidAPI = retrofit.create(CovidAPI.class);
  3. Call<StateMainModel> call = covidAPI.getAllIndiaStates();
  4. call.enqueue(new Callback<StateMainModel>() {
  5. @Override
  6. public void onResponse(Call<StateMainModel> call, Response<StateMainModel> response) {
  7. if(!response.isSuccessful())
  8. {
  9. Toast.makeText(getApplicationContext(),"Error!!Code: "+response.code()+response.toString(),Toast.LENGTH_SHORT).show();
  10. tv.setText(response.toString());
  11. return;
  12. }
  13. else
  14. {
  15. StateMainModel stateMainModel = response.body();
  16. int size = stateMainModel.getStates().size();
  17. for(int i=0;i<size;i++)
  18. {
  19. stateList.add(stateMainModel.getStates().get(i).getState_name());
  20. }
  21. stateAutoCompleteTextView.setAdapter(stateAdapter);
  22. }
  23. }
  24. @Override
  25. public void onFailure(Call<StateMainModel> call, Throwable t) {
  26. Toast.makeText(getApplicationContext(),"Error!! Response: "+t.getMessage(),Toast.LENGTH_LONG).show();
  27. }
  28. });

api接口

  1. @GET("v2/admin/location/states")
  2. Call<StateMainModel> getAllIndiaStates();

StateMain模型类

  1. private ArrayList<StateIdNameModel> states;
  2. private Integer ttl;
  3. public StateMainModel() {
  4. }
  5. public StateMainModel(ArrayList<StateIdNameModel> states,Integer ttl) {
  6. this.states = states;
  7. this.ttl = ttl;
  8. }
  9. public ArrayList<StateIdNameModel> getStates() {
  10. return states;
  11. }
  12. public void setStates(ArrayList<StateIdNameModel> states) {
  13. this.states = states;
  14. }
  15. public Integer getTtl() {
  16. return ttl;
  17. }
  18. public void setTtl(Integer ttl) {
  19. this.ttl = ttl;
  20. }
mrphzbgm

mrphzbgm1#

您必须在请求中设置用户代理才能获得成功的响应。请参阅以下kotlin代码:

  1. val okHttpClientBuilder = OkHttpClient.Builder()
  2. val logger = HttpLoggingInterceptor().apply { level = Level.BODY}
  3. okHttpClientBuilder.addNetworkInterceptor { chain ->
  4. chain.proceed(chain.request()
  5. .newBuilder()
  6. .header("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36")
  7. .build())
  8. }.addNetworkInterceptor(logger)
  9. val retrofit = Retrofit.Builder()
  10. .baseUrl("https://cdn-api.co-vin.in/api/v2/")
  11. .client(okHttpClientBuilder.build())
  12. .addConverterFactory(MoshiConverterFactory.create())
  13. .build()

相关问题