按标签搜索FlickR照片

时间:2016-08-20 01:18:22

标签: java android rest retrofit flickr

我正在尝试查询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);
   }

}

1 个答案:

答案 0 :(得分:1)

根据他们的API docs,您希望将text作为@Query参数而不是q。所以喜欢:

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

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