【发布时间】:2016-07-24 00:28:24
【问题描述】:
我正在使用 Retrofit,我想根据用户输入的搜索词查询 FlickR。我想确保正确设置它,因为我在 Retrofit/REST 方面的经验有限。任何关于我的代码的教程、建议和评论都将不胜感激。
我已将一些项目标记为“不确定”,我不知道应该输入的确切内容。在 REST 中,“q”是否总是用来表示查询?
最后,我希望图像结果显示在 GridView 中并可供用户选择:
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&tags=<mQuery>&api_key=1c448390199c03a6f2d436c40defd90e&format=json") //
Call<List<Photo>> getPhotos(@Query("q") String photoSearchTerm);
}
}
【问题讨论】:
标签: java android retrofit flickr