2016-02-18 19 views
1

我看到的每个示例和教程都展示了如何将请求体转换为JSON,而我并不需要这样做。改装2请求身体没有JSON,只是一个正常的形式?

它不是有效的在我的情况下,因为我不与节点或w/e交谈,我会浪费计算,我将不得不在我的应用程序中转换为json,然后从我的LEMP服务器中的json解码期待有规律的表格,我没有理由这样做。

到目前为止我试过了什么?每一个教程/例子,我可以找到。

public interface myClient { 
    @GET("api/fetch-all") 
    Call<List<ServiceGenerator.Data>> data(); 

    //how am i supposed to do this? 
    @POST("api/login") 
    Call<ServiceGenerator.Cookie> fetchCookie(@Body String email, String password); 
} 

回答

1

我使用这样的

class User { 
    String email; 
    String password; 

    public User(String email, String password) { 
     this.email = email; 
     this.password = password; 
    } 
} 

,然后像你说的

@FormUrlEncoded 
@POST("api/login") 
Call<User> fetchCookie(@Field("email") String email, @Field("password") String password); 

User user = new User("[email protected]", "1234"); 
mService.fetchCookie(user.email, user.password) 

这样你最终使用FormURLEncoded方法后。另外,Retrofit提供了一些方法来覆盖它的默认转换器ResponseBodyRequestBody。正如文件中指出:

改造配置

改造是通过它的API接口被打开 成可调用的对象类。默认情况下,Retrofit会为您的平台提供默认的 ,但它允许自定义。

转换器

默认情况下,改造只能反序列化HTTP机构进入OkHttp的 ResponseBody类型,它只能接受其 @Body RequestBody类型。

可以添加转换器来支持其他类型。为了您的方便,六个兄弟模块 适应流行的序列化库。

GSON:com.squareup.retrofit2:转换器-GSON杰克逊: com.squareup.retrofit2:转换器 - 杰克逊莫希: com.squareup.retrofit2:转换器-莫希的Protobuf: com.squareup.retrofit2:转换器 - protobuf导线: com.squareup.retrofit2:converter-wire简单XML: com.squareup.retrofit2:converter-simplexml标量(原语,装箱, 和String):com.squareup.retrofit2:转换器标量以下是一个 示例使用GsonConverterFactory类生成GitHubService接口的实现,该接口使用Gson的 反序列化。

Retrofit retrofit = new Retrofit.Builder() 
    .baseUrl("https://api.github.com") 
    .addConverterFactory(GsonConverterFactory.create()) 
    .build(); 

GitHubService service = retrofit.create(GitHubService.class); 

自定义转换

如果您需要与使用内容的格式, 改造不支持开箱即用的API通信(如YAML,TXT,自定义 格式)或者您希望使用不同的库来实现现有格式,您可以轻松创建自己的转换器。创建一个扩展了Converter的 类。工厂类,并在构建适配器时传入 。

希望它有帮助