我尝试在程序包Route中设置一个定义为静态变量的动态变量,但我不了解它如何与Retrofit一起使用。
导入静态de.package.tradilianz.DashboardRetailer.retailerid;
公共接口APIInterface {
@Headers("Content-Type: application/json")
@POST("retailers/{param}/products")
Call<Product> createProduct(@Body Product product @Param("param") id = retailerid);
}
如何正确设置{param}?我以为我可以将Retailerid编写为静态String并导入到我的Interface Class中,然后将其声明为@Param,但它无法正常工作。我想说id = retailerId应该在@POST(“ retailers / {param} / products”}
中设置我还尝试设置@POST(“ retailers /” + retailerid +“ / products”),但变量必须为常量。好吧,我在活动中得到了变量Retailerid,但我没有任何常数。
我的活动分类:
public class RetailerProductActivity extends AppCompatActivity {
private SharedPreferences prefs;
public static String id;
APIInterface apiInterface;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_retailer_product);
context = this;
prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
//Get retailerIdfrom SharedPreference
String serializedDataFromPreference = prefs.getString("RetailerResponseObject", null);
Retailer retailer = Retailer.create(serializedDataFromPreference);
id = retailer.getId();
}
public void onClickProduct(View v){
apiInterface = APIClient.getClient(ipAddress).create(APIInterface.class);
Product product = new Product("994", "Marlboro", "Marlborolight", 8.5, "Tabakwaren",
"1");
// POST product
Call<Product> call1 = apiInterface.createProduct(product);
call1.enqueue(new Callback<Product>() {
@Override
public void onResponse(Call<Product> call, Response<Product> response) {
if(response.isSuccessful()){
try{
Product prodct1 = response.body();
Log.w("Der Response body",prodct1.toString() );
//speichern in sharedPrefence fehlt
}catch (NullPointerException e){
e.printStackTrace();
}
}else{
Toast.makeText(context, "Erreiche den Server nicht :/! Wurde der Server gestartet?",Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<Product> call,Throwable t) {
call.cancel();
Log.w("onResponse: ", "POST Response probleme", t.getCause());
}
});
}
}
[您有意见的人请帮助
您可以这样创建动态网址:
@Headers("Content-Type: application/json")
@POST
Call<Product> createProduct(@Url String URL, @Body Product product);
您需要使用Path而不是Param
@Headers("Content-Type: application/json")
@POST("retailers/{param}/products")
Call<Product> createProduct(@Body Product product @Path("param") String value);
// Inside you onClickProduct just pass your value.
Call<Product> call1 = apiInterface.createProduct(product,"Put you Value Here");