如何将GET参数传递给Retrofit请求
我正在使用SoundCloud api创建一个应用程序并尝试追加用户输入的字符串值,但它在界面中显示为null如何将其追加到url中?
MainActivity.java
b.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View p1) { // TODO: Implement this method search = et.getText().toString(); Log.d("search",search); Intent i = new Intent(MainActivity.this, SoundCloud.class); i.putExtra("mysearch", search); startActivity(i); Log.d("CustomUrl",SCService.CustomUrl); Toast.makeText(MainActivity.this,""+SCService.CustomUrl,Toast.LENGTH_SHORT).show(); Retrofit retrofit = new Retrofit.Builder() .baseUrl(Config.API_URL) .addConverterFactory(GsonConverterFactory.create()).build(); SCService Scservice = retrofit.create(SCService.class); Call
ScService.java
public interface SCService { public String CustomUrl = Config.API_URL+"/resolve.json?url="+SoundCloud.SCURL+"&client_id="+Config.CLIENT_ID; @GET("/resolve.json?url={SCURL}"+"&client_id="+Config.CLIENT_ID) Call getTrack(@Path("SCURL")String SCURL); }
搜索字符串在我的SoundCloud.java类中
SCURL = receivedmsg.getString("mysearch"); Log.d("intentdata",SCURL); tv.setText("Search Results for " + SCURL);
我想在GET参数中追加SCURL String,但是它显示了SCURL的空值,我怎么能实现这个呢?
更新:我已经更改了我的代码,但是出现了这个错误
enter code here 03-15 13:22:14.866 6149 6149 D search com.sk.scdoenloader /https://m.soundcloud.com/dharmaworldwide/houseofcards-mixmaster-05b 03-15 13:22:14.967 6149 6149 D CustomUrl com.sk.scdoenloader https://api.soundcloud.com/resolve.json?url=null&client_id=iZIs9mchVcX5lhVRyQGGAYlNPVldzAoX 03-15 13:22:15.299 6149 6149 E AndroidRuntime com.sk.scdoenloader FATAL EXCEPTION: main 03-15 13:22:15.299 6149 6149 E AndroidRuntime com.sk.scdoenloader Process: com.sk.scdoenloader, PID: 6149 03-15 13:22:15.299 6149 6149 E AndroidRuntime com.sk.scdoenloader java.lang.IllegalArgumentException: No Retrofit annotation found. (parameter #1) 03-15 13:22:15.299 6149 6149 E AndroidRuntime com.sk.scdoenloader for method SCService.getTrack 03-15 13:22:15.299 6149 6149 E AndroidRuntime com.sk.scdoenloader at retrofit2.ServiceMethod$Builder.methodError(ServiceMethod.java:720) 03-15 13:22:15.299 6149 6149 E AndroidRuntime com.sk.scdoenloader at retrofit2.ServiceMethod$Builder.methodError(ServiceMethod.java:711) 03-15 13:22:15.299 6149 6149 E AndroidRuntime com.sk.scdoenloader at retrofit2.ServiceMethod$Builder.parameterError(ServiceMethod.java:729) 03-15 13:22:15.299 6149 6149 E AndroidRuntime com.sk.scdoenloader
你必须在这里使用@Path
@GET("/resolve.json?url={url}&client_id={clientId}") Call getTrack(@Path("url") String url,@Path("clientId") String clientId);
您可以使用DYNAMIC URL进行改造!! (使用@Get
)
public interface SCService{ @GET public Call getTrack(@Url String url); }
然后,您可以使用自定义字符串URL进行调用
service.getTrack("/resolve.json?url="+SoundCloud.SCURL+"&client_id="+ Config.CLIENT_ID + SCURL)
你想要的是GET参数,而不是路径,所以使用@Query("scurl") String scurl
更多细节在这里
顺便说一句,对你的变量名使用全部大写是有点奇怪的(至少在Java中), scurl
比SCURL
更合适