我正在尝试查询FlickR照片并接收JSON响应。我正在使用Retrofit来调用FlickR API。在我的代码中,用户输入文本,该文本通过EditText捕获。我想根据这个词查询。我从Flick收到以下错误:“无参数搜索已被禁用。请改用flickr.photos.getRecent。”

public class MainActivity extends AppCompatActivity {

private EditText mSearchTerm;
private Button mRequestButton;
private String mQuery;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mSearchTerm = (EditText) findViewById(R.id.ediText_search_term);
    mRequestButton = (Button) findViewById(R.id.request_button);
    mRequestButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mQuery = mSearchTerm.getText().toString();
            HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
            interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl("https://api.flickr.com/services/rest/")
                    .client(client)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();


            ApiInterface apiInterface = retrofit.create(ApiInterface.class);
            Call<List<Photo>> call = apiInterface.getPhotos(mQuery);
            call.enqueue(new Callback<List<Photo>>() {
                @Override
                public void onResponse(Call<List<Photo>> call, Response<List<Photo>> response) {

                }

                @Override
                public void onFailure(Call<List<Photo>> call, Throwable t) {

                }
            });

        }
    });



}

//Synchronous vs. Asynchronous
public interface ApiInterface {
    @GET("?&method=flickr.photos.search&api_key=1c448390199c03a6f2d436c40defd90e&format=json")  //
    Call<List<Photo>> getPhotos(@Query("q") String photoSearchTerm);
   }

}

最佳答案

基于他们的API docs,您希望将text作为@Query参数而不是q传递。像这样:

Call<List<Photo>> getPhotos(@Query("text") String photoSearchTerm);

其他事情:
•可能想从您的帖子中隐藏您的API密钥。
•可能想用onClick()将代码包装在if(!TextUtils.isEmpty(mQuery))方法中,以防止再次发生此问题。 (还可以将TextChangeWatcher添加到您的EditText中,并根据EditText中字符串的长度启用/禁用搜索按钮

10-07 13:41
查看更多