我正在尝试使用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);
同样的错误:/