【发布时间】:2018-09-05 08:40:26
【问题描述】:
我正在尝试使用Microsoft translator API 翻译一些文本。我正在使用Retrofit 2。这是代码:
public RestClient() {
final OkHttpClient httpClient = new OkHttpClient.Builder()
.addNetworkInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
final Request originalRequest = chain.request();
Request newRequest;
newRequest = originalRequest.newBuilder()
.header("Content-Type", "application/json")
.header("Ocp-Apim-Subscription-Key", "KEY")
.header("X-ClientTraceId", java.util.UUID.randomUUID().toString())
.build();
return chain.proceed(newRequest);
}
})
.addNetworkInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
.build();
// Build the retrofit config from our http client
final Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.cognitive.microsofttranslator.com/")
.client(httpClient)
.addConverterFactory(GsonConverterFactory.create())
.build();
// Build api instance from retrofit config
api = retrofit.create(RestApi.class);
}
public interface RestApi {
@POST("translate?api-version=3.0&from=en&to=zh-Latn")
Call<TranslationResultDTO> getTranslation(@Body final RequestBody Text);
}
public void getTranslation(final String text, final RestCallback<TranslationResultDTO> translationResultCallback) {
final JsonObject jsonBody = new JsonObject();
jsonBody.addProperty("Text", text);
RequestBody textToTranslateBody = RequestBody.create(MediaType.parse("application/json"), jsonBody.toString());
Call<TranslationResultDTO> call = api.getTranslation(textToTranslateBody);
call.enqueue(new Callback<TranslationResultDTO>() {
@Override
public void onResponse(Call<TranslationResultDTO> call, retrofit2.Response<TranslationResultDTO> response) {
final int responseCode = response.code();
....
}
@Override
public void onFailure(Call<TranslationResultDTO> call, Throwable t) {
....
}
});
}
我从服务器收到一个错误。该错误表明正文不是有效的JSON。
有人知道问题出在哪里吗? 提前致谢!
更新
这是我也尝试过的另一个解决方案的代码。此解决方案使用 POJO 类:
public class Data {
@SerializedName("Text")
private String text;
public Data(String text) {
this.text = text;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
@POST("translate?api-version=3.0&from=en&to=zh-Latn")
Call<TranslationResultDTO> getTranslation(@Body final Data Text);
Data data = new Data("text value to translate");
Call<TranslationResultDTO> call = api.getTranslation(data);
同样的错误:/
【问题讨论】:
标签: android post request retrofit2