当前位置:网站首页>基于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转JavaBean

返回的json内容如下:

{
    "message": [
        {
            "key": "hello",
            "paraphrase": "n.“喂”的招呼声或问候声;int.哈喽,喂,你好,您好,表示问候,打招呼",
            "value": 0,
            "means": [
                {
                    "part": "int.",
                    "means": [
                        "哈喽,喂",
                        "你好,您好",
                        "表示问候",
                        "打招呼"
                    ]
                },
                {
                    "part": "n.",
                    "means": [
                        "“喂”的招呼声或问候声"
                    ]
                }
            ]
        }
    ],
    "status": 1
}

效果图:

案例代码:

  1. 需要依赖的第三方库

    //在build.gradle文件下
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
    
  2. AndroidManifest.xml中打开网络访问权限

    <uses-permission android:name="android.permission.INTERNET"/>
    
  3. 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 +
                    '}';
        }
    }
    
  4. 自定义请求接口: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);
    }
    
  5. 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();
        }
    }
    
  6. 布局界面: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>
    
原网站

版权声明
本文为[砖厂打工仔]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_42456748/article/details/125211628