当前位置:网站首页>基于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>
边栏推荐
- 【推薦系統 01】Rechub
- A case of compiling QT file qmake compiling script
- 滚动踩坑--UNI_APP(八)
- Laya common script commands
- Simple and easy to modify spring frame components
- PostgreSQL中的表复制
- After the uniapp jumps to the page in onlaunch, click the event failure solution
- 2022.7.5DAY597
- 请问申购新股哪个证券公司开户是最好最安全的
- "Dream Cup" 2017 Jiangsu information and future primary school summer camp it expert PK program design questions
猜你喜欢
How to prepare for the advanced soft test (network planning designer)?
Wallhaven壁纸桌面版
Find the root of equation ax^2+bx+c=0 (C language)
单调性约束与反单调性约束的区别 monotonicity and anti-monotonicity constraint
2021-04-23
What does intermediate software evaluator test
Arduino board description
verilog设计抢答器【附源码】
[machine learning 03] Lagrange multiplier method
在线硬核工具
随机推荐
[untitled]
What is an intermediate network engineer? What is the main test and what is the use?
Ffmpeg record a video command from RTSP
QT document
Mendeley -- a free document management tool that automatically inserts references into papers
The fifth training assignment
Multithreaded application (thread pool, singleton mode)
Transaction rolled back because it has been marked as rollback only
BUUCTF---Reverse---reverse1
【C#】WinForm运行缩放(变糊)的解决方法
[pytorch 07] hands on deep learning chapter_ Preliminaries/ndarray exercises hands-on version
mif 文件格式记录
2021 summary and 2022 outlook
Unity script visualization about layout code
Socket socket programming
Interprocess communication (IPC)
Une fois que l'uniapp a sauté de la page dans onlaunch, cliquez sur Event Failure resolution
[untitled]
Unity script generates configurable files and loads
After the uniapp jumps to the page in onlaunch, click the event failure solution