由于马上要考四六级,但是每次查单词都要查百度,非常的麻烦啊,为了能够更好的查单词,我开发了一个简单的安卓查单词的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"><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"tools:context=".MainActivity"><EditTextandroid:id="@+id/edit_text"android:layout_height="wrap_content"android:layout_width="300dp"></EditText><Buttonandroid:id="@+id/button"android:layout_width="100dp"android:layout_height="wrap_content"android:text="提交" /></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"tools:context=".MainActivity"><TextViewandroid: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) { //导入URLnew Thread(new Runnable() {@Overridepublic 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() {@Overridepublic 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;@Overrideprotected 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() {@Overridepublic 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() {@Overridepublic 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() {@Overridepublic 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,所以说要学会知识的迁移啊!

然后祝大家四六级都通过!

如何用Android Stuido 调用百度翻译的API相关推荐

  1. python调用百度翻译-Python 调用百度翻译API

    由于实习公司这边做的是日文app,有时要看看用户反馈,对于我这种五十音图都没记住的人,表示百度翻译确实还可以.但不想每次都复制粘贴啊,google被墙也是挺蛋疼的事,所以用python结合baidu ...

  2. 用java多线程实现“百度翻译接口API快速翻译”

    不知道为啥,突然开始想写博客,可能是想找个地方写点东西,煽情文艺的咱写不了,就写技术贴好了.不当之处,还希望同志们多多指教,不胜感激. API准备:自己先到百度去申请一个百度翻译API,话说百度翻译还 ...

  3. python百度翻译接口_python3 调用百度翻译API翻译英文

    自行申请百度开发者账号import importlib,sys,urllib importlib.reload(sys) import urllib.request import json #导入js ...

  4. access百度翻译 get_Asp.NET调用百度翻译

    Asp.NET调用百度翻译,图示: HTML: OA翻译 TextMode="MultiLine"> 源语言: 自动检测 中文 英文 日文 目标语言: 自动检测 中文 英文 ...

  5. python百度翻译api申请网页版_python3调用百度翻译api接口实现全过程

    现在很都平台的翻译api接口都开始收费了,比如谷歌.微软.yandex等等,注册非常麻烦,而且要钱,目前就百度还剩下一个最基础的翻译api不需要钱,今天我要和大家分享的是怎样使用python3调用百度 ...

  6. Android Studio调用百度地图(二):实现地图显示后台定位和步行导航

    先看一下运行效果: 实现功能:后台定位+步行导航(可通过长按屏幕自定义终点,起点为定位点) 后台定位即当程序在后台时依旧执行定位功能,步行导航支持30米-50千米范围内的导航 一 导入SDK并配置相关 ...

  7. requests基操/爬取调用百度翻译

    因为最近使用pandas 和numpy,所以就研究下requests库,毕竟这是目前python最流行的http请求库,也是最符合pythonic的库,有时间也准备看源码学习下,不过前一阵看到一个ht ...

  8. 【2019-07-23】]python3 把日语翻译为中文 调用百度翻译API接口及API申请使用教程

    点击申请百度翻译API,得到一个你自己的API账户. 点击查看申请教程,感谢教程原作者. API官网提供了一个python2的使用接口的demo还有详细的解释文档 想用python3完成,代码几乎照搬 ...

  9. Python3调用百度翻译API进行英文翻译

    一.API的概念 API(Application Programming Interface,应用程序编程接口)是一些预先定义的函数,目的是提供应用程序与开发人员基于某软件或硬件得以访问一组例程的能力 ...

  10. C#调用百度翻译API实现自己的简单翻译工具

    前几天因为频繁使用翻译功能,但是市面上的翻译软件都臃肿了,对我我这个只需要翻译的人没有什么太大用处,反而有更多弊端. 于是在百度开发者中心申请了一个百度翻译的API.自己写了一个简单的翻译功能.仅供自 ...

最新文章

  1. 合工大建筑和计算机专业哪个好,合肥工业大学最好的专业是什么(10大热门专业排名)...
  2. (chap4 IP协议) IP协议
  3. DataGridView的DataGridViewComboBoxColumn列点击一次
  4. 史上最全的JUC并发图
  5. 如何在程序中不用加号实现加法_程序员那些事 | JavaScript基础(六)
  6. bzoj2282 [Sdoi2011]消防 直径+二分+树dp
  7. Scratch:海龟绘图(九)
  8. 多线程访问DataTable
  9. 带有分页的列表的跳转后,返回时怎么实现保留分页的页数等信息
  10. Avalon二数据填充
  11. [雪峰磁针石博客]软件测试专家工具包2性能测试
  12. 通达信c语言接口,通达信数据接口及日线数据格式
  13. 卷不能在读/写模式下重新挂载。可能是因为先前没有完全卸载(安全删除)
  14. 【rzxt】巧用电池小工具 电量问题全掌握
  15. vue alert内含有html,vue一步步实现alert功能
  16. 如何在不改SQL的情况下优化数据库- 云和恩墨优化专家罗海雄
  17. 从云大会谈谈云计算“关键”技术趋势
  18. C++定义结构体大小根堆的方法
  19. Linux 2.6.19.x 内核编译配置选项简介(内核裁剪)
  20. 寻找打地鼠游戏制作者

热门文章

  1. java 模块层次结构图_Spring框架模块结构图解析
  2. 阻滞增长模型求解_阻滞增长模型
  3. DAS、SAN和NAS三种存储方式
  4. iOS开发中Certificates,IdentifiersProfiles各种证书配置文件总结
  5. oracle 同义词public,oracle中private同义词跟public同义词
  6. 2022清明节放假安排来了,制定假日计划可用云便签软件
  7. 淘宝开放平台 ISV入驻开发流程
  8. iphone屏幕圆角插件_苹果iPhone6s也能分屏?越狱新插件助你实现
  9. 双非本科地信前端面试题目
  10. Linux-whereis find locat which半解