700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > AndroidStudio - - - 有道翻译接口调用

AndroidStudio - - - 有道翻译接口调用

时间:2021-07-20 01:40:56

相关推荐

AndroidStudio - - - 有道翻译接口调用

完整项目文件:/Zichen1016/csdn-2027140351

使用Okhttp框架和Gson开源类库,可以在GitHub上查阅API文档。

/square/okhttp

/google/gson

1. 逻辑代码

1.1 MainActivity 类

package com.example.myapplication;import androidx.appcompat.app.AppCompatActivity;import okhttp3.Call;import okhttp3.Callback;import okhttp3.OkHttpClient;import okhttp3.Request;import okhttp3.Response;import android.os.Bundle;import android.text.Editable;import android.util.Log;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;import com.example.myapplication.model.Fanyi;import com.google.gson.Gson;import com.google.gson.reflect.TypeToken;import org.jetbrains.annotations.NotNull;import java.io.IOException;import java.lang.reflect.Type;public class MainActivity3 extends AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main4);Button btn1 = findViewById(R.id.fan_yi); // 翻译按钮final EditText editText = findViewById(R.id.yuan_wen); // 原文输入final TextView textView = findViewById(R.id.yi_wen); // 翻译后的文本btn1.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {Editable yuanWen = editText.getText();String url = "/translate?doctype=json&i=" + yuanWen;// Log.i("tag", url);// TODO http请求OkHttpClient okHttpClient = new OkHttpClient();Request request = new Request.Builder().url(url).get() // 默认就是GET请求,可以不写.build();Call call = okHttpClient.newCall(request);call.enqueue(new Callback() {// Callback回调函数 请求数据获取后执行@Overridepublic void onFailure(@NotNull Call call, @NotNull IOException e) {Log.e("tag", e.toString());}@Overridepublic void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {String responseDate = response.body().string();Gson gson = new Gson();Type MembersType = new TypeToken<Fanyi>() {}.getType();Fanyi fanYi = gson.fromJson(responseDate,MembersType);// 转换成FanYi类String translateResult = fanYi.getTranslateResult().get(0).get(0).getTgt();Log.i("tag",translateResult +"");textView.setText(translateResult);}});}});}}

1.2 Fanyi 类

有道翻译接口返回的数据如图:

将json数据解析为java对象列表结构。

package com.example.myapplication.model;import java.util.ArrayList;public class Fanyi {private String type;private int errorCode;private int elapsedTime;private ArrayList<ArrayList<translateResult>> translateResult;public Fanyi() {}public Fanyi(String type, int errorCode, int elapsedTime, ArrayList<ArrayList<translateResult>> translateResult) {this.type = type;this.errorCode = errorCode;this.elapsedTime = elapsedTime;this.translateResult = translateResult;}public String getType() {return type;}public void setType(String type) {this.type = type;}public int getErrorCode() {return errorCode;}public void setErrorCode(int errorCode) {this.errorCode = errorCode;}public int getElapsedTime() {return elapsedTime;}public void setElapsedTime(int elapsedTime) {this.elapsedTime = elapsedTime;}public ArrayList<ArrayList<translateResult>> getTranslateResult() {return translateResult;}public void setTranslateResult(ArrayList<ArrayList<translateResult>> translateResult) {this.translateResult = translateResult;}}

1.3 translateResult 类

package com.example.myapplication.model;public class translateResult {private String src;private String tgt;public translateResult() {}public translateResult(String src, String tgt) {this.src = src;this.tgt = tgt;}public String getSrc() {return src;}public void setSrc(String src) {this.src = src;}public String getTgt() {return tgt;}public void setTgt(String tgt) {this.tgt = tgt;}}

2. 布局代码

2.1 XML 文件

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="/apk/res/android"xmlns:app="/apk/res-auto"xmlns:tools="/tools"android:layout_width="match_parent"android:layout_height="match_parent"tools:context=".MainActivity3"android:orientation="vertical"><EditTextandroid:id="@+id/yuan_wen"android:layout_width="match_parent"android:layout_height="300dp"android:gravity="top"android:textSize="25sp"android:textStyle="bold"android:text="今天天气真好!"/><Buttonandroid:id="@+id/fan_yi"android:layout_width="match_parent"android:layout_height="70dp"android:text="翻译"android:textSize="25sp"/><TextViewandroid:id="@+id/yi_wen"android:layout_width="match_parent"android:layout_height="300dp"android:text=""android:textSize="25sp"/></LinearLayout>

3.配置代码

3.1 build.gradle 文件

apply plugin: 'com.android.application'android {compileSdkVersion 30buildToolsVersion "30.0.2"defaultConfig {applicationId "com.example.myapplication"minSdkVersion 16targetSdkVersion 30versionCode 1versionName "1.0"testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"}buildTypes {release {minifyEnabled falseproguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'}}}// 指定当前项目的所有依赖关系:本地依赖、库依赖、远程依赖dependencies {implementation fileTree(dir: "libs", include: ["*.jar"]) // 本地依赖implementation 'androidx.appcompat:appcompat:1.2.0'implementation 'androidx.constraintlayout:constraintlayout:2.0.1'implementation 'androidx.legacy:legacy-support-v4:1.0.0'implementation 'androidx.navigation:navigation-fragment:2.1.0'implementation 'androidx.navigation:navigation-ui:2.1.0'testImplementation 'junit:junit:4.12' // 测试用例库androidTestImplementation 'androidx.test.ext:junit:1.1.2'androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'// 远程依赖,com.squareup.okhttp3是域名部分,okhttp是组名称,4.2.1是版本号implementation 'com.squareup.okhttp3:okhttp:4.2.1'implementation 'com.google.code.gson:gson:2.8.6'}

3.2 AndroidManifest.xml 文件

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="/apk/res/android"package="com.example.myapplication"><applicationandroid:allowBackup="true"android:icon="@mipmap/ic_launcher"android:label="@string/app_name"android:networkSecurityConfig="@xml/network_config"android:roundIcon="@mipmap/ic_launcher_round"android:supportsRtl="true"android:theme="@style/AppTheme.NoActionBar"><activity android:name=".MainActivity3"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity><activity android:name=".MainActivity2" /><activity android:name=".MainActivity" /></application><!-- 配置INTERNET权限 --><uses-permission android:name="android.permission.INTERNET" /><!-- 配置INTERNET权限 --></manifest>

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。