매개 변수를 사용하여 개조 및 GET
Retrofit을 사용하여 Google GeoCode API에 요청을 보내려고합니다. 서비스 인터페이스는 다음과 같습니다.
public interface FooService {
@GET("/maps/api/geocode/json?address={zipcode}&sensor=false")
void getPositionByZip(@Path("zipcode") int zipcode, Callback<String> cb);
}
서비스에 전화 할 때 :
OkHttpClient okHttpClient = new OkHttpClient();
RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(Constants.GOOGLE_GEOCODE_URL).setClient(new OkClient(okHttpClient)).build();
FooService service = restAdapter.create(FooService.class);
service.getPositionByZip(zipCode, new Callback<String>() {
@Override public void success(String jsonResponse, Response response) {
...
}
@Override public void failure(RetrofitError retrofitError) {
}
});
다음 스택 추적을받습니다.
06-07 13:18:55.337: E/AndroidRuntime(3756): FATAL EXCEPTION: Retrofit-Idle
06-07 13:18:55.337: E/AndroidRuntime(3756): Process: com.marketplacehomes, PID: 3756
06-07 13:18:55.337: E/AndroidRuntime(3756): java.lang.IllegalArgumentException: FooService.getPositionByZip: URL query string "address={zipcode}&sensor=false" must not have replace block.
06-07 13:18:55.337: E/AndroidRuntime(3756): at retrofit.RestMethodInfo.methodError(RestMethodInfo.java:120)
06-07 13:18:55.337: E/AndroidRuntime(3756): at retrofit.RestMethodInfo.parsePath(RestMethodInfo.java:216)
06-07 13:18:55.337: E/AndroidRuntime(3756): at retrofit.RestMethodInfo.parseMethodAnnotations(RestMethodInfo.java:162)
06-07 13:18:55.337: E/AndroidRuntime(3756): at
StackOverflow 질문을 살펴 보았습니다. Retrofit : @GET 명령의 여러 쿼리 매개 변수? 그러나 그것은 적용 가능하지 않은 것 같습니다.
http://square.github.io/retrofit/ 에서 코드를 거의 그대로 가져 왔 으므로 문제를 이해하는 데 약간의 손실이 있습니다.
생각?
AFAIK {...}는 쿼리 매개 변수 내부가 아닌 경로로만 사용할 수 있습니다. 대신 이것을 시도하십시오.
public interface FooService {
@GET("/maps/api/geocode/json?sensor=false")
void getPositionByZip(@Query("address") String address, Callback<String> cb);
}
전달할 매개 변수의 양을 알 수없는 경우 다음과 같이 사용할 수 있습니다.
public interface FooService {
@GET("/maps/api/geocode/json")
@FormUrlEncoded
void getPositionByZip(@FieldMap Map<String, String> params, Callback<String> cb);
}
@QueryMap 대신 나를 위해 일했다 FieldMap
GET 매개 변수가 많은 경우 URL에 전달하는 또 다른 방법은 HashMap.
class YourActivity extends Activity {
private static final String BASEPATH = "http://www.example.com";
private interface API {
@GET("/thing")
void getMyThing(@QueryMap Map<String, String> params, new Callback<String> callback);
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
RestAdapter rest = new RestAdapter.Builder().setEndpoint(BASEPATH).build();
API service = rest.create(API.class);
Map<String, String> params = new HashMap<String, String>();
params.put("key1", "val1");
params.put("key2", "val2");
// ... as much as you need.
service.getMyThing(params, new Callback<String>() {
// ... do some stuff here.
});
}
}
The URL called will be http://www.example.com/thing/?key1=val1&key2=val2
I also wanted to clarify that if you have complex url parameters to build, you will need to build them manually. ie if your query is example.com/?latlng=-37,147, instead of providing the lat and lng values individually, you will need to build the latlng string externally, then provide it as a parameter, ie:
public interface LocationService {
@GET("/example/")
void getLocation(@Query(value="latlng", encoded=true) String latlng);
}
Note the encoded=true is necessary, otherwise retrofit will encode the comma in the string parameter. Usage:
String latlng = location.getLatitude() + "," + location.getLongitude();
service.getLocation(latlng);
Complete working example in Kotlin, I have replaced my API keys with 1111...
val apiService = API.getInstance().retrofit.create(MyApiEndpointInterface::class.java)
val params = HashMap<String, String>()
params["q"] = "munich,de"
params["APPID"] = "11111111111111111"
val call = apiService.getWeather(params)
call.enqueue(object : Callback<WeatherResponse> {
override fun onFailure(call: Call<WeatherResponse>?, t: Throwable?) {
Log.e("Error:::","Error "+t!!.message)
}
override fun onResponse(call: Call<WeatherResponse>?, response: Response<WeatherResponse>?) {
if (response != null && response.isSuccessful && response.body() != null) {
Log.e("SUCCESS:::","Response "+ response.body()!!.main.temp)
temperature.setText(""+ response.body()!!.main.temp)
}
}
})
참고URL : https://stackoverflow.com/questions/24100372/retrofit-and-get-using-parameters
'Program Club' 카테고리의 다른 글
| 인터페이스 속성의 XML 직렬화 (0) | 2020.10.11 |
|---|---|
| JavaScript-HTML 양식 값 가져 오기 (0) | 2020.10.11 |
| TypeError : 일관된 메서드 확인 순서 (MRO)를 만들 수 없습니다. (0) | 2020.10.11 |
| Axios로 양식에서 파일을 게시하는 방법 (0) | 2020.10.11 |
| Swift에서 UIImage에 색상을 지정하려면 어떻게해야합니까? (0) | 2020.10.10 |