接口: 我输入单词到文本,然后单击按钮,在输出中输入结果
public interface Link {
@FormUrlEncoded//аннотация
@POST("https://translate.yandex.net/api/v1.5/tr.json/translate")
Call<Object> translate(@FieldMap Map<String,String> map);
}
如何在后台线程中运行改造?
我输入单词到文本,然后单击按钮,在输出结果,简单的翻译器,我测试这个库
答案 0 :(得分:7)
call.execute();
是同步网络调用,不应在主线程上执行。
正如他们向您指出的那样,您最好的选择是使用call.enqueue()
,如下所示:
call.enqueue(new Callback<Object>() {
@Override
public void onResponse(Call<Object> call, Response<Object> response) {
response = response.body();
}
@Override
public void onFailure(Call<Object> call, Throwable t) {
}
如果来电成功,您会在onResponse
onFailure
其他人处获得回复
答案 1 :(得分:1)
使用com.squareup.retrofit2:retrofit:2.1.0
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call1, retrofit2.Response<ResponseBody> response) {
BufferedReader reader = null;
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(response.body().byteStream()));
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
result = sb.toString();
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e("Tag","onResponse onFailure" );
}
});