当前位置:网站首页>基于Retrofit框架的金山API翻译功能案例
基于Retrofit框架的金山API翻译功能案例
2022-07-07 09:04:00 【砖厂打工仔】
基于Retrofit框架的金山API翻译功能案例
这里使用的API如下,可使用浏览器或postman查看。
https://dict-mobile.iciba.com/interface/index.php?c=word&m=getsuggest&nums=1&is_need_mean=1&word=hello
以上为翻译hello单词意思,如需要翻译其他,只需改变word=hello的值即可。
此次访问使用的是get请求,返回一个Json字符串,并对Json字符串进行反序列化转换为JavaBean。另外JavaBean可使用网站自动生成,输入返回的Json对象即可。网址如下:
返回的json内容如下:
{
"message": [
{
"key": "hello",
"paraphrase": "n.“喂”的招呼声或问候声;int.哈喽,喂,你好,您好,表示问候,打招呼",
"value": 0,
"means": [
{
"part": "int.",
"means": [
"哈喽,喂",
"你好,您好",
"表示问候",
"打招呼"
]
},
{
"part": "n.",
"means": [
"“喂”的招呼声或问候声"
]
}
]
}
],
"status": 1
}
效果图:
案例代码:
需要依赖的第三方库
//在build.gradle文件下 implementation 'com.squareup.retrofit2:retrofit:2.9.0' implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
AndroidManifest.xml中打开网络访问权限
<uses-permission android:name="android.permission.INTERNET"/>
JavaBean:
Translation.java
public class Translation { private List<Message> message; private int status; public void setMessage(List<Message> message) { this.message = message; } public List<Message> getMessage() { return message; } public void setStatus(int status) { this.status = status; } public int getStatus() { return status; } @Override public String toString() { return "Translation{" + "message=" + message + ", status=" + status + '}'; } }
Message.java
public class Message { private String key; private String paraphrase; private int value; private List<Means> means; public void setKey(String key) { this.key = key; } public String getKey() { return key; } public void setParaphrase(String paraphrase) { this.paraphrase = paraphrase; } public String getParaphrase() { return paraphrase; } public void setValue(int value) { this.value = value; } public int getValue() { return value; } public void setMeans(List<Means> means) { this.means = means; } public List<Means> getMeans() { return means; } @Override public String toString() { return "Message{" + "key='" + key + '\'' + ", paraphrase='" + paraphrase + '\'' + ", value=" + value + ", means=" + means + '}'; } }
Means.java
public class Means { private String part; private List<String> means; public void setPart(String part) { this.part = part; } public String getPart() { return part; } public void setMeans(List<String> means) { this.means = means; } public List<String> getMeans() { return means; } @Override public String toString() { return "Means{" + "part='" + part + '\'' + ", means=" + means + '}'; } }
自定义请求接口:GetRequest_interface
public interface GetRequest_interface { @GET("interface/index.php?c=word&m=getsuggest&nums=1&is_need_mean=1") Call<Translation> getCall(@Query("word") String word); }
MainActivity.java
public class MainActivity extends AppCompatActivity { private EditText et; private Button btn; private TextView tv; private Handler handler = new Handler(Looper.getMainLooper()); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btn = findViewById(R.id.btn_trans); tv = findViewById(R.id.result); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //这里有个小坑,当想要提取TextView的对象时,需要将findViewById()放到点击事件中 et = findViewById(R.id.et_word); String content = et.getText().toString().trim(); request(content); } }); } private void request(String str) { new Thread(new Runnable() { @Override public void run() { Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://dict-mobile.iciba.com/") .addConverterFactory(GsonConverterFactory.create()) .build(); GetRequest_interface request = retrofit.create(GetRequest_interface.class); Call<Translation> call = request.getCall(str); Response<Translation> response = null; try { response = call.execute(); } catch (IOException e) { e.printStackTrace(); } Translation translation = response.body(); String result = translation.getMessage().get(0).getParaphrase(); handler.post(new Runnable() { @Override public void run() { tv.setText(result); } }); } }).start(); } }
布局界面:activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <EditText android:id="@+id/et_word" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="请输入需要翻译的单词:" /> <Button android:id="@+id/btn_trans" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:text="翻译" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="50dp" android:text="翻译结果:" android:textColor="@color/black" android:textSize="20sp" /> <TextView android:id="@+id/result" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="50dp" /> </LinearLayout>
边栏推荐
- Some online academic report websites and machine learning videos
- How to prepare for the advanced soft test (network planning designer)?
- "Dream Cup" 2017 Jiangsu information and future primary school summer camp it expert PK program design questions
- Idea shortcut keys
- SQL Server knowledge gathering 9: modifying data
- Bookmarking - common website navigation for programmers
- Shardingsphere sub database and table examples (logical table, real table, binding table, broadcast table, single table)
- 2021 summary and 2022 outlook
- mif 文件格式记录
- What if copying is prohibited?
猜你喜欢
seata 1.3.0 四種模式解决分布式事務(AT、TCC、SAGA、XA)
2021-04-23
Deep understanding of Apache Hudi asynchronous indexing mechanism
Monai version has been updated to 0.9. See what new functions it has
Force buckle 1002 Find common characters
What are the test preparation materials and methods for soft exam information processing technicians?
Online hard core tools
MPX plug-in
The gun startles the dragon, and the crowd "locks" Zhou Zhi
Using tansformer to segment three-dimensional abdominal multiple organs -- actual battle of unetr
随机推荐
【OneNote】无法连接到网络,无法同步问题
Operation method of Orange Pie orangepi 4 lts development board connecting SATA hard disk through mini PCIe
Basic knowledge of process (orphan, zombie process)
从色情直播到直播电商
Mpx 插件
BUUCTF---Reverse---reverse1
Unity determines whether the mouse clicks on the UI
[untitled]
[STM32] actual combat 3.1 - drive 42 stepper motors with STM32 and tb6600 drivers (I)
2021-04-23
Go-Redis 中间件
Idea shortcut keys
單調性約束與反單調性約束的區別 monotonicity and anti-monotonicity constraint
滚动踩坑--UNI_APP(八)
Cmake learning manual
Compile QT project script with qmake
Unable to open kernel device '\.\vmcidev\vmx': operation completed successfully. Reboot after installing vmware workstation? Module "devicepoweron" failed to start. Failed to start the virtual machine
Unity script generates configurable files and loads
Wallhaven壁纸桌面版
V-for img SRC rendering fails