我想解析与Retrofit和Gson的JSON文件。问题是URL接受参数forceDeviceId
。如果此值设置为-111
,则可以恢复正确的文件。默认情况下,这个参数设置为-1
和一个404错误被抛出:改造忽略查询参数
我尝试了两种方法:硬编码的API URL参数并使用查询:
// either hardcoded in the URL
@GET("de/product/productlistajax.json?forceDeviceId=-111")
Call<ProductListParent> loadProductList(
@Query("categoryId") String categoryId,
@Query("sort") String sort,
@Query("lazyLoading") String lazyLoading,
// alternatively use this query
@Query("forceDeviceId") String forceDeviceId
);
但是这两种方法都返回了404。所以我想知道我错过了什么让它工作(就像它在浏览器中一样)。我还认识到,在加载浏览器中的URL后,立即删除该参数。那么这是他们后端阻止的事情吗?
这里是方法,其中我打电话:
@Subscribe
public void getProductListRequest(MMSATServices.ProductListRequest request) {
final MMSATServices.ProductListResponse productListResponse = new MMSATServices.ProductListResponse();
productListResponse.productListParent = new ProductListParent();
Call<ProductListParent> call = liveApi.loadProductList(
request.categoryId, request.sort, request.lazyLoading, request.forceDeviceId);
call.enqueue(new Callback<ProductListParent>() {
@Override
public void onResponse(Call<ProductListParent> call, Response<ProductListParent> response) {
productListResponse.productListParent = response.body();
bus.post(productListResponse);
}
@Override
public void onFailure(Call<ProductListParent> call, Throwable t) {
t.printStackTrace();
}
});
}
这是错误消息我得到:
Response{protocol=http/1.1, code=404, message=Not Found, url=https://www.mediamarkt.de/de/product/productlistajax.json?categoryId=563612&sort=topseller&lazyLoading=true}
编辑:这里是我创建的改造对象
private static Retrofit createMMSATService(String baseUrl) {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(interceptor)
.cookieJar(new CustomCookieJar())
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
return retrofit;
}
与CustomCookieJAr
类别:
public class CustomCookieJar implements CookieJar {
private List<Cookie> cookies = new ArrayList<>();
@Override
public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
if (cookies != null) {
this.cookies = cookies;
}
}
@Override
public List<Cookie> loadForRequest(HttpUrl url) {
return cookies;
}
}
正在讨论的工作API和你从代码中调用的API是不同的 –
我编辑了一下,我认为它们应该是相同的。此外,如果你从错误消息中复制url,它将在浏览器中工作 – 4ndro1d