如何在改造API方法中传递POST参数?

kom*_*rma 4 rest android retrofit

我正在编写我的第一个代码Retrofit 1.9.我试图关注几个博客,但无法理解非常基本的问题.到目前为止,我已经创建Model使用类jsonschema2pojo,RestAdapter类.

这是我的模型类:

@Generated("org.jsonschema2pojo")
public class GmailOauth {

@Expose
private String createdAt;
@Expose
private String objectId;
@Expose
private String sessionToken;
@Expose
private String username;

.....  Getter and Setter methods...
Run Code Online (Sandbox Code Playgroud)

我已经创建了上面的model类Jsonschema2pojo.所以,我的回答JSON是非常容易理解的.

适配器类

public class RestApiAdapter {
public static final String BASE_URL = "http://testingserver.com:8081";
public RestAdapter providesRestAdapter(Gson gson) {
    return new RestAdapter.Builder()
            .setEndpoint(BASE_URL)
            .build();
   }
}
Run Code Online (Sandbox Code Playgroud)

API类

interface GmailSignInAPI {

@POST("/signWithGmail")
void GmailOauthLogin(@Body GmailOauth user, Callback<GmailOauth> cb);

}
Run Code Online (Sandbox Code Playgroud)

现在,我很困惑如何编写Retrofit客户端以following高效的方式传递form-data post参数?

accessToken  (String value)
userID       (String value)
Run Code Online (Sandbox Code Playgroud)

如果我想在post请求中传递自定义对象并将请求的响应保存在同一对象中怎么样?这是一个很好的方法吗?

Jos*_*her 10

我认为对于Retrofit的api部分我会说

 @FormUrlEncoded
    @Post("/path/to/whatever")
    void authenticateWithSomeCredentials(@Field("username") String userName, Callback<Object> reponse
Run Code Online (Sandbox Code Playgroud)

然后我会这样称呼它:

public void authenticateWithSomeCredentials(username), new Callback<Object>() {

   @Override
   public void success(Object object, Response response) {
   // Do something
    }

   @Override
   public void failure(RetrofitError error) {
    // Do something
    }

}
Run Code Online (Sandbox Code Playgroud)

要将令牌添加到每个调用,您可以添加拦截器:

public class YourAuthInterceptor implements interceptor {

@Override
public Response intercept(Chain chain) throws IOException {
     request = chain.request().newBuilder()
     .addHeader("token"), tokenVariable)
     .build();
return chain.proceed(request);
    }
}
this will add a "token" to every call you make with retrofit

so then when you build your api you build it like this

YourApi api = new RestAdapter.Builder()
            .setEndpoint(url)
            .setRequestInterceptor(new YourAuthInterceptor())
            .build()
            .create(YourApi.class);
Run Code Online (Sandbox Code Playgroud)

我希望这很有意义,因为我很快就打字了.如果您有任何疑问,请告诉我.