I am trying to translate some text by using Microsoft translator API. I am using Retrofit 2
. This is the code:
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) {
....
}
});
}
I get an error from the server. The error says that the body in not a valid JSON
.
Does someone know where is the problem?? Thanks in advance!
UPDATE
Here is the code for another solution I have tried as well. This solution is using a POJO class:
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);
Also the same error :/