java - android Retrofit2 无法添加 header (415 错误代码)

标签 java android retrofit2 okhttp skyscanner

我正在尝试通过 skyscanner api 访问票证数据并将其传递到我的 View ,但我无法完成此操作,因为我收到 415 错误代码 我正在使用 Retrofit2 并以编程方式添加 header 。我的界面如下所示:

public interface GetFlightDetails {

@POST("apiservices/pricing/v1.0/")
Call<TicketData> getFlightList(@Query("apiKey") String apiKey,
                                @Query("country") String country,
                                @Query("currency") String currency,
                                @Query("locale") String locale,
                                @Query("originPlace") String originPlace,
                                @Query("destinationPlace") String destinationPlace,
                                @Query("outboundPartialDate")String outboundPartialDate,
                                @Query("inboundPartialDate") String inboundPartialDate,
                                @Query("locationschema") String locationschema,
                                @Query("cabinclass") String cabinclass,
                                @Query("adults") int adults,
                                @Query("children") int children,
                                @Query("infants") int infants,
                                @Query("groupPricing") boolean groupPricing) ;
}

在我的 Activity 中,当我准备好发出请求时,我有以下代码:

Gson gson = new GsonBuilder()
            .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
            .create();


    OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
    //adding logging
    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    logging.setLevel(HttpLoggingInterceptor.Level.BASIC);
    httpClient.interceptors().add(logging);
    //headers
    httpClient.addInterceptor(new Interceptor() {
        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            Request original = chain.request();

            //adding header info
            Request request = original.newBuilder()
                    .header("Content-Type", "application/x-www-form-urlencoded")
                    .header("Accept", "application/json")
                    .method(original.method(), original.body())
                    .build();

            return chain.proceed(request);
        }
    });

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .client(httpClient.build())
            .build();

    GetFlightDetails api = retrofit.create(GetFlightDetails.class);

    Call<TicketData> mresponse = api
            .getFlightList(API_KEY, country, currency, locale, from, to,
                    departDate.substring(0,10), returnDate.substring(0,10),
                    locationSchema, cabinClass, adult, children, infants, false);

    mresponse.enqueue(new Callback<TicketData>()
    {
        @Override
        public void onResponse(Call<TicketData> call, Response <TicketData> response) {

            if (!response.isSuccessful()){
                Log.d("UnSuccess", response.raw().toString());
                return;
            }
            else {
                progress.cancel(); //cancel progress dialog
                Log.d("Success", response.raw().toString());
                TicketData ticketData = response.body();

                RecyclerAdapter adapter = new RecyclerAdapter(getApplicationContext(), ticketData);
                mRecyclerView.setAdapter(adapter);
            }
        }

        @Override
        public void onFailure(Call<TicketData> call, Throwable t){
            progress.setMessage("Retrofit Error Occured");
        }
    });

在我的日志文件中我看到以下错误:

com.example.ex D/OkHttp: --> POST http://partners.api.skyscanner.net/apiservices/pricing/v1.0/?apiKey=xxxxxxxx&country=US&currency=USD&locale=en-us&originPlace=SFO&destinationPlace=LAX&outboundPartialDate=2016-10-24&inboundPartialDate=2016-10-31&locationschema=iata&cabinclass=Economy&adults=1&children=0&infants=0&groupPricing=false http/1.1 (0-byte body)
com.example.ex D/OkHttp: <-- 415 Unsupported Media Type http://partners.api.skyscanner.net/apiservices/pricing/v1.0/?apiKey=xxxxxxxx&country=US&currency=USD&locale=en-us&originPlace=SFO&destinationPlace=LAX&outboundPartialDate=2016-10-24&inboundPartialDate=2016-10-31&locationschema=iata&cabinclass=Economy&adults=1&children=0&infants=0&groupPricing=false (403ms, 0-byte body)
com.example.ex D/UnSuccess: Response{protocol=http/1.1, code=415, message=Unsupported Media Type, url=http://partners.api.skyscanner.net/apiservices/pricing/v1.0/?apiKey=xxxxxxxx&country=US&currency=USD&locale=en-us&originPlace=SFO&destinationPlace=LAX&outboundPartialDate=2016-10-24&inboundPartialDate=2016-10-31&locationschema=iata&cabinclass=Economy&adults=1&children=0&infants=0&groupPricing=false}

我不确定为什么会发生这种情况,因为我尝试在界面中添加 header 。

Skyscanner 文档 reference 1reference 2

谢谢!

最佳答案

请引用同类型示例:检查你的参数类型,哪个字段是查询字符串,哪个字段是@Field等,

public static final String TRAVEL_API = "http://business.skyscanner.net/";

public interface TravelApiInterface {

    @FormUrlEncoded
    @Headers("Content-Type:application/x-www-form-urlencoded; charset=UTF-8")
    @POST("/apiservices/pricing/v1.0/")

    void getTravelApi(
        @Field("country") String country,
        @Field("currency") String currency,
        @Field("locale") String locale,
        @Field("locationSchema") String locationSchema,
        @Field("apikey") String apikey,
        @Field("grouppricing") String grouppricing,
        @Field("originplace") String originplace,
        @Field("destinationplace") String destinationplace,
        @Field("outbounddate") String outbounddate,
        @Field("inbounddate") String inbounddate,
        @Field("adults") int adults,
        @Field("children") int children,
        @Field("infants") int infants,
        @Field("cabinclass") String cabinclass, Callback<Object> response);
}

TravelApiInterface 货币请求接口(interface)服务;

    RestAdapter adapter = new RestAdapter.Builder()
            .setEndpoint(Url.TRAVEL_API)
            .setRequestInterceptor(new RequestInterceptor() {
                @Override
                public void intercept(RequestFacade request) {
                    request.addQueryParam(getString(R.string.api_key_title), getString(R.string.api_key_value));
                }
            })
            .setLogLevel(RestAdapter.LogLevel.FULL)
            .build();

    currencyRequestInterfaceService = adapter.create(TravelApiInterface.class);

==================== 示例请求

requestConversion("UK", "GBP", "en-GB", "iata", "xxxxxxxx","on", "EDI", "LHR", 
    "2016-10-04", "2016-10-11", 1, 0, 0, "Economy", new Callback<Object>() {

                @Override
                public void success(Object o, Response response) {

                }

                @Override
                public void failure(RetrofitError error) {

                }
});

在 strings.xml 中

<string name="api_key_title">apikey</string>
<string name="api_key_value">xxxxxxx</string>

关于java - android Retrofit2 无法添加 header (415 错误代码),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39717209/

相关文章:

android - 网络pojo类和数据库实体类,如何避免重复

java - JOOQ批处理语句中的绑定(bind)调用次数是否有上限?

java - 如何检查字符串中有多少个非字母数字字符

java - easymock - 模拟使用 anyObject 作为 void setter 方法的参数

java - 如何在 UI 中显示字符限制以及为用户数字化了多少?安卓Java

android - MPAndroidChart BarChart 禁用右侧图例

java - JPA 标准 - 获取子实体而不是根实体

java - 如何在 android 上的 textView 中设置 List<String>

java - 如何使用 id 在 URL android 中传递 "?",因为我的 url 如下所示

android - 如何在没有搜索 View 的情况下单击一组按钮后过滤回收 View