由于马上要考四六级,但是每次查单词都要查百度,非常的麻烦啊,为了能够更好的查单词,我开发了一个简单的安卓查单词的APP,我们来看一看如何实现这个应用
我们先来看一看布局,所有元素放到大的LinearLayout里面,元素是垂直分布,然后在这里面,每一行放一个LinearLayout,这样就实现了换行。
//activity_main.xml
```<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
tools:context=".MainActivity">
<EditText
android:id="@+id/edit_text"
android:layout_height="wrap_content"
android:layout_width="300dp"></EditText>
<Button
android:id="@+id/button"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="提交" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="match_parent"
android:layout_height="585dp" />
</LinearLayout>
</LinearLayout>
然后就是具体功能的实现了
我用的是百度翻译的API
网站和导入详情可以在这个网站去看
https://api.fanyi.baidu.com/doc/21
前面的输入都很好搞定,就是自己的appid,随机数随便输
但是这个签名要把三个字符连在一起,还要进行MD5的转码
所以还要写一个MD5的转码函数
但是谢谢万能的CSDN,让我找到了MD5转码的代码
原作者 https://blog.csdn.net/cnnumen/article/details/8286536
public static String stringToMD5(String string) {
byte[] hash;
try {
hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
StringBuilder hex = new StringBuilder(hash.length * 2);
for (byte b : hash) {
if ((b & 0xFF) < 0x10)
hex.append("0");
hex.append(Integer.toHexString(b & 0xFF));
}
return hex.toString();
}
然后终于获得了JSON解析的内容
{“from”:“en”,“to”:“zh”,“trans_result”:[{“src”:“apple”,“dst”:"\u82f9\u679c"}]}
其实解析这个JSON还是很简单的
在trans_result中提取dst就可以了
但是\u82f9\u679c是什么鬼?
然后发现是UNicode码,但是发现好像不需要转码,安卓会自动识别
然后我们进行解析就可以了
先获取我们的URL
String str = edit_text.getText().toString();
String side = "你的appid"+str+"随机数"+"key";
String fi_side = stringToMD5(side); //进行MD5加密
String url = "https://fanyi-api.baidu.com/api/trans/vip/translate?q="+str+"&from=auto&to=zh&appid=自己的appid&salt=随机数&sign="+fi_side; // 再将前面一大堆连接即可
sendRequestWithOkHttp2(url);
为了能够解析我们的JSON我们还需要在build.gradle加上几行代码
注意是在app文件夹的build不要加错位置
dependencies {
implementation 'com.google.code.gson:gson:2.7' //加上这几行
implementation 'com.squareup.okhttp3:okhttp:3.4.1'
}
别忘了申请网络权限
在AndroidManifest里面加上
<uses-permission android:name="android.permission.INTERNET" />
写解析代码
private void sendRequestWithOkHttp2(String url) { //导入URL
new Thread(new Runnable() {
@Override
public void run() {
try {
Log.d("MainActivty","abcd");
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
// 指定访问的服务器地址是电脑本机
.url(url)
.build();
Response response = client.newCall(request).execute();
String responseData = response.body().string(); // responseData是我们得到的数据,但是数据没有进行提取
parseJSONWithGSON(responseData); // 解析JSON函数,对我们需要的部分进行提取
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
解析JSON数据 在trans_result中提取dst,再用主线程更新UI
private void parseJSONWithGSON(String json) throws JSONException {
try {
JSONObject jsonObject1 = new JSONObject(json);
JSONArray jsonArray = jsonObject1.getJSONArray("trans_result");
JSONObject jsonObject = (JSONObject) jsonArray.get(0);
String name = jsonObject.getString("dst");
showResponse(name); // 在主线程更新UI
}
catch (Exception e) {
e.printStackTrace();
}
}
更新UI,主线程更新
private void showResponse(String name) {
runOnUiThread(new Runnable() {
@Override
public void run() {
// 在这里进行UI操作,将结果显示到界面上
textview.setText(name);
}
});
}
然后我们这个APP就开发完毕了
我们看看我们Java里面的完整代码吧
package com.example.myapplication21;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
private EditText edit_text;
private TextView textview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edit_text = (EditText) findViewById(R.id.edit_text);
textview = (TextView) findViewById(R.id.text_view);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String str = edit_text.getText().toString();
String side = "20211214001028426"+str+"123456aIYg8uxQqeeGsCra26ft";
Log.d("MainActivty","1321");
Log.d("MainActivty",side);
String fi_side = stringToMD5(side);
Log.d("MainActivty",fi_side);
String url = "https://fanyi-api.baidu.com/api/trans/vip/translate?q="+str+"&from=auto&to=zh&appid=20211214001028426&salt=123456&sign="+fi_side;
Log.d("MainActivty",url);
sendRequestWithOkHttp2(url);
}
});
}
public static String stringToMD5(String string) {
byte[] hash;
try {
hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
StringBuilder hex = new StringBuilder(hash.length * 2);
for (byte b : hash) {
if ((b & 0xFF) < 0x10)
hex.append("0");
hex.append(Integer.toHexString(b & 0xFF));
}
return hex.toString();
}
private void sendRequestWithOkHttp2(String url) {
new Thread(new Runnable() {
@Override
public void run() {
try {
Log.d("MainActivty","abcd");
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
// 指定访问的服务器地址是电脑本机
.url(url)
.build();
Response response = client.newCall(request).execute();
String responseData = response.body().string();
Log.d("MainActivty",responseData );
parseJSONWithGSON(responseData);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
private void showResponse(String name) {
runOnUiThread(new Runnable() {
@Override
public void run() {
// 在这里进行UI操作,将结果显示到界面上
textview.setText(name);
}
});
}
private void parseJSONWithGSON(String json) throws JSONException {
try {
JSONObject jsonObject1 = new JSONObject(json);
JSONArray jsonArray = jsonObject1.getJSONArray("trans_result");
JSONObject jsonObject = (JSONObject) jsonArray.get(0);
String name = jsonObject.getString("dst");
showResponse(name);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
我们来看一看运行的效果
了解了百度翻译的API的调用和解析其实是个万金油,我们可以通过利用这个技术解析各种各样的API,不瞒大家说之前我搞了一个新闻的app,花了一个星期的时间,但是了解了之后,只花了30分钟就搞成功了百度翻译的app,所以说要学会知识的迁移啊!
然后祝大家四六级都通过!