使用Retrofit 2发送带有url参数的帖子

Max*_*ude 2 java android retrofit2

我想发送一个带有Retrofit 2的POST.该url有一些参数:

 @Headers({
      "Accept: application/x-www-form-urlencoded;",
      "User-Agent: my-app"
 })
 @FormUrlEncoded
 @POST("server/directory/location.type")
`public Call<POJOStringValue> dataWithUr(@Path("arg1") String arg1, @Path("arg2"), String arg2);         
Run Code Online (Sandbox Code Playgroud)

网址看起来像这样

www.website.com/server/directory/location.type?arg1=value1&arg2=value2

我被要求使用POST请求.值(value1和value2)在运行时是动态的.我使用HttpClient与Xamarin开始了这个项目,现在我用Java native重写它.在C#中,我所要做的就是完成字符串并将结果字符串发送到一个Post中.

我试图使用@Path,错误是:

"server/directory/location.type"不包含"{arg1}".(参数#1)

然后,我尝试使用@Query,错误是:

java.lang.IllegalArgumentException:表单编码方法必须至少包含一个@Field.

最后我尝试使用@Field请求永远不会得到任何响应(我将连接超时设置为5秒)

请帮助我,或告诉我是否必须有其他选择,只能使用GET请求.

((编辑)) 这是我的客户端设置代码:

private static void setupClient(){
    final OkHttpClient client = new okhttp3.OkHttpClient.Builder()
            .connectTimeout(CONNECTION_TIMEOUT, TimeUnit.SECONDS)
            .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
            .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)
            .retryOnConnectionFailure(false)
            .build();


    //define retrofit
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(iXUtils.getUrl_())
            .addConverterFactory(GsonConverterFactory.create())
            .client(client)
            .build();

    this.client_ = retrofit.create(RequestInterface.class);
}
Run Code Online (Sandbox Code Playgroud)

get()方法:

public static RequestInterface get(){
    return this.client_;
}
Run Code Online (Sandbox Code Playgroud)

以下是我的称呼方式:

 public String callFunctionDB(String arg1,  String arg2){
    setupClient();

    Call<POJOStringValue> call  = get().dataWithUrlString(arg1, arg2);
    try {
        POJOStringValue response = call.execute().body();
        String value = response.getValue();
        int test = 0;
    } catch (IOException e) {
        String value = "it failded";
        e.printStackTrace();
    }
    return "test";
} 
Run Code Online (Sandbox Code Playgroud)

我把test = 0放到了一个突破点,它永远不会到达那里.另外,我在doInbackground中调用方法"callFunctionDB"以避免android.os.NetworkOnMainThreadException.

iag*_*een 10

如果您请求表单编码,则Retrofit要求您至少拥有一个表单参数.您已经回答了自己的问题 - 您正在使用查询参数而不是POST字段,因此不需要注释.删除@FormUrlEncoded注释,并将参数更改为@Query注释.