【发布时间】:2017-04-20 08:58:15
【问题描述】:
我正在尝试使用 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}
编辑:这是我创建 Retrofit 对象的方式
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,它将在浏览器中运行
标签: android json gson retrofit