使用Retrofit2,无法在POST请求中发送JSON正文

时间:2017-04-28 10:10:05

标签: java android post retrofit retrofit2

我正在使用以下代码来实现一个使用POST方法的API和原始JsonObject作为正文。

public interface PostRawJsonService {
    @POST
    Call<Model> submitData(@Url String url, @HeaderMap Map<String, String> headers, @Body Email email);
}

电子邮件模型是:

public class Email {
    private String email;

    public Email(String email) {
        this.email = email;
    }
}

我这样称呼它:

Email email= new Email("team@gmail.com");
Call<Model> call = service.submitData(url, headers, email);

这不起作用,代码似乎停留在Call<Model> call = service.submitData(url, headers, email);行,并且日志也没有显示任何错误。可能是什么问题?

我打印请求时,如下:

{   "body": {
    "contentType": {
      "mediaType": "application/json",
      "subtype": "json",
      "type": "application"
    }   },   "headers": {
    "namesAndValues": [
      "Authorization",
      "xyz"
    ]   },   "method": "POST",   "url": {
    "host": "my.company.com",
    "password": "",
    "pathSegments": [
      "data",
      "next",
      "email"
    ],
    "port": 443,
    "scheme": "https",
    "url": "https://my.company.com/data/next/email",
    "username": ""   } }

2 个答案:

答案 0 :(得分:0)

在Email类中创建getter和setter方法:

public class Email {
    private String email;

    public Email(String email) {
        this.email = email;
    }

    public String getEmail(){
      return this.email;
    }

    public void setEmail(String email){
      this.email = email;
    }
}

答案 1 :(得分:0)

HashMap<String, String> headerMap = new HashMap<>();
headerMap.put("SessionID", "Session");
headerMap.put("UserName", "Username");
headerMap.put("Content-Type", "application/json");

OkHttpClient httpClient = // Create OkHttpClient

我使用此方法获取httpclient:

public OkHttpClient addHeaders(final HashMap<String, String> headerMap) {
    return new OkHttpClient.Builder()
            .addInterceptor(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request.Builder builder = chain.request().newBuilder();
                    Set<String> keySets = headerMap.keySet();
                    for (String key : keySets) {
                        builder.addHeader(key, headerMap.get(key));
                    }
                    return chain.proceed(builder.build());
                }
            })
            .readTimeout(60, TimeUnit.SECONDS)
            .connectTimeout(60, TimeUnit.SECONDS)
            .build();
}

PostRawJsonService service = ConnectToService
        .newInstance()
        .getClient(httpClient).create(PostRawJsonService.class);

这里ConnectToService是我用来创建改造的常用类。您可以在自己现在使用的课程中使用它。

通过将正文放在前面并将网址放到下一个来进行服务:

Call<Model> call = service.submitData(email, url);