我正在用 Retrofit 1.9
版本编写我的第一个代码。我试着关注几个博客,但无法理解非常基本的问题。到目前为止,我已经使用 jsonschema2pojo
、RestAdapter
类创建了 Model
类。
这是我的模型类:
@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...
我使用 Jsonschema2pojo
创建了上面的 model
类。所以,我的响应 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();
}
}
API类
interface GmailSignInAPI {
@POST("/signWithGmail")
void GmailOauthLogin(@Body GmailOauth user, Callback<GmailOauth> cb);
}
现在,我很困惑如何编写 Retrofit
客户端以有效地传递 following
表单数据发布参数?
accessToken (String value)
userID (String value)
如果我想在 post 请求中传递自定义对象并将请求的响应保存在同一个对象中怎么办?这种方法好吗?
最佳答案
我想我会把 Retrofit 的 api 部分放在
@FormUrlEncoded
@Post("/path/to/whatever")
void authenticateWithSomeCredentials(@Field("username") String userName, Callback<Object> reponse
然后我会这样调用它:
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
}
}
要将 token 添加到您可以添加拦截器的每个调用:
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);
我希望这是有道理的,因为我正在快速输入它。如果您有任何问题,请告诉我。
关于android - 如何在改造 API 方法中传递 POST 参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32591056/