【问题标题】:GET query with json - Retrofit 2.0使用 json 获取查询 - Retrofit 2.0
【发布时间】:2016-07-05 11:18:33
【问题描述】:

如何进行这个我将在下面提到的查询?

方法@GET。查询应如下所示:

/top40?data={"ranking":"world"} /top40?data={"ranking":"country"}

@GET("/api/top40")
    Call<FamousTop40Model> getStatus(
        // what should be there?
    );

    class Factory {
        private static FamousTop40Api service;

        public static FamousTop40Api getInstance() {
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(ApiConstants.BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();

            service = retrofit.create(FamousTop40Api.class);

            return service;
        }
    }

你们能帮帮我吗?

编辑:+ 我应该在标题中有accessKey

【问题讨论】:

  • 您要发出 Get 或 Put 请求吗?
  • 获取请求,但在收到的 API 中说我应该发送 json 来接收数据。甚至可以在 Get 中发送 json 参数?
  • 您可以按照下面的答案。@y07k2
  • @y07k2 是的,可以发送 json,但我不确定是否可以使用 GET 发送,但请参考此链接以使用 POST stackoverflow.com/questions/21398598/… 发送 json

标签: android json gson retrofit


【解决方案1】:

这对我有帮助:

public interface FamousTop40Api {
    @GET("/api/top40")
    Call<FamousTop40Model> getStatus(
            @Query("data") String ranking
    );

    class Factory {
        private static FamousTop40Api service;

        public static FamousTop40Api getInstance() {
            OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
            httpClient.addInterceptor(new Interceptor() {
                @Override
                public Response intercept(Interceptor.Chain chain) throws IOException {
                  Request original = chain.request();

                  Request request = original.newBuilder()
                          .header("accessKey", MainActivity.ACCESS_KEY)
                          .method(original.method(), original.body())
                          .build();

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

            OkHttpClient client = httpClient.build();

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

            service = retrofit.create(FamousTop40Api.class);

            return service;
        }
    }
}

所以你需要在标题中添加@QueryaccessKeyOkHttpClient

FamousTop40Api.Factory.getInstance().getStatus("{\"ranking\":\"country\"}").enqueue();

【讨论】:

    【解决方案2】:

    你可以这样调用你的 GET 方法:

    public interface EndPointInterface{
    @GET(ProximityConstants.URL_FETCH_STORE_INFO)
        Call<Store> getStoreInfoByBeaconUUID(@Query(ProximityConstants.BEACON_UUID) String beaconUUID);
    
    }
    

    要调用 GET 方法 webservice 像这样继续:

     Call<StoreSettings> call = apiService.getStoreSettings(mStore.getStoreID(), mCustomer.getCustId(),
                    mStore.getBeaconID(), ProximityConstants.SETTINGS_CUST_TYPE, ProximityConstants.ACTION_STORE_VISIT);
            call.enqueue(new Callback<StoreSettings>() {
                @Override
                public void onResponse(Call<StoreSettings> call, Response<StoreSettings> response) {
                    ProximityUtil.writeLog(TAG, "Received store settings");
                    mStoreSettings = response.body();
                    SharedPreferences.Editor editor = mAppPreferences.edit();
                    editor.putString(ProximityConstants.SETTINGS_OBJ_STORE_SETTINGS, new Gson().toJson(mStoreSettings));
                    editor.commit();
                    Intent intent = new Intent(BeaconScanService.this, ProximityWelcomeActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    BeaconScanService.this.startActivity(intent);
                }
    
                @Override
                public void onFailure(Call<StoreSettings> call, Throwable t) {
                    Toast.makeText(BeaconScanService.this, "Error: " + t.getMessage(), Toast.LENGTH_LONG).show();
                }
            });
    

    【讨论】:

    • @Query("ranking") String ranking 将使用?data={...} 创建此请求?我在哪里可以添加标题?
    • 没有得到你,在你的获取服务中你需要传递参数或标题吗?
    • 我没听懂。 accessKey 在标头中,data json 包含 ranking 在参数中的字符串值。
    【解决方案3】:

    尝试如下:创建类Task.java:

    public class Task {  
    private String ranking;
    
    public Task(String ranking) {
        this.ranking = ranking;
    }
    }
    

    然后执行以下操作:

    public interface TaskService {  
    
    @POST("/top40?data=")
    Call<Top40Model> getStatus(@Body Task task);
    
    }
    

    并使用如下:

    Task task = new Task("world");  
    Task task = new Task("country");  
    
    Call<Top40Model> call=new Factory.getInstance().getStatus(task);
    call.enqueue(new Callback<Top40Model>() {});
    

    【讨论】:

    • "data={"ranking":"{ranking}"}" 如何用字符串值替换ranking?原因例如此网址在 Postman http://5.135.147.222:8400/api/top40?data={"ranking":"world"} 中有效。请注意,{..} 包含所有参数
    • 使用@Query 时出现错误:IllegalArgumentException: URL query string "data={"ranking":"{ranking}"}" must not have replace block. For dynamic query parameters use @Query.。我认为必须存在括号...
    • 他说的是 GET,而不是 POST。
    • 是的,body json 用于 POST 请求,但问题是询问 URL 中的 json 对象
    猜你喜欢
    • 2014-03-14
    • 2016-10-03
    • 2015-12-24
    • 2017-04-08
    • 1970-01-01
    • 2021-12-17
    • 1970-01-01
    • 2016-02-19
    • 2022-01-21
    相关资源
    最近更新 更多