异步操作读取网络的json数据(有道翻译实例)

做了一个翻译的软件,调用的有道的翻译。总结下有道翻译页面的出现的问题。

 

1.将String数据,转化为utf-8的数据

//将获取的字符串,转换成utf-8编码
        try {
            content = new String(content.getBytes("UTF-8"));
            content = URLEncoder.encode(content, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

 

2.从有道的api中获取返回的接送数据

try {
                    BufferedReader reader = new BufferedReader(new InputStreamReader
                            (new URL(url).openStream(), "utf-8"));
                    String line = null;
                    StringBuffer content = new StringBuffer();
                    while ((line = reader.readLine()) != null) {
                        content.append(line);
                    }
                    reader.close();
                    return content.toString();
                } catch (IOException e) {
                    e.printStackTrace();
                }

其中返回的content.toString就是返回的数据,这个就是读取返回的json数据了,联网操作,要把他放在异步操作里面。

3.从json数据里面解析出来自己想要的数据。

         JSONObject jsonObject = new JSONObject(s);
         JSONObject basicJs = new JSONObject((jsonObject.getJSONObject("basic")).toString());
         JSONArray arr = basicJs.getJSONArray("explains");
         String explains = arr.getString(0);
         System.out.println("翻译:" + jsonObject.getString("translation"));
         System.out.println("读音" + basicJs.getString("phonetic"));
         System.out.println("explains" + explains);
         doneshow.setText("翻译:" + jsonObject.get("translation") + "\n读音:"
          + basicJs.getString("phonetic") + "\n解释:" + explains);

其实,s为一个json的数据,JSONObject表示对象,JSONArray表示数组。

 

4.源码问题

public class TranslationActivity extends AppCompatActivity {

    private String content, url;
    private Button bt_translate;
    private TextView doneshow;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fanyi);

        doneshow = (TextView) findViewById(R.id.done);
        bt_translate = (Button) findViewById(R.id.bt_translate);

        bt_translate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                translation();
            }
        });
    }

    private void translation() {
        content = ((EditText) findViewById(R.id.et_content)).getText().toString().trim();
        //将获取的字符串,转换成utf-8编码
        try {
            content = new String(content.getBytes("UTF-8"));
            content = URLEncoder.encode(content, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        url = "http://fanyi.youdao.com/openapi.do?keyfrom=aiyouv&key=
        1417254817&type=data&doctype=json&version=1.1&q=" + content;
        System.out.println(url + "112233344");
        doneshow.setText("loading..");
        new AsyncTask<Void, Void, String>() {
            @Override
            protected String doInBackground(Void... params) {

                try {
                    BufferedReader reader = new BufferedReader(new InputStreamReader
                            (new URL(url).openStream(), "utf-8"));
                    String line = null;
                    StringBuffer content = new StringBuffer();
                    while ((line = reader.readLine()) != null) {
                        content.append(line);
                    }
                    reader.close();
                    return content.toString();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }

            //这个方法是自带的,执行完一步操作之后那,运行的方法
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                if (s != null) {
                    try {

                        JSONObject jsonObject = new JSONObject(s);
                        JSONObject basicJs = new JSONObject((jsonObject.getJSONObject("basic"))
.toString());
                        JSONArray arr = basicJs.getJSONArray("explains");
                        String explains = arr.getString(0);
                        System.out.println("翻译:" + jsonObject.getString("translation"));
                        System.out.println("读音" + basicJs.getString("phonetic"));
                        System.out.println("explains" + explains);
                        doneshow.setText("翻译:" + jsonObject.get("translation")
 + "\n读音:" + basicJs.getString("phonetic") + "\n解释:" + explains);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.execute();
    }
}

 

5.(番外)如何读取网络数据,并且打印出来

 

public class MainActivity extends AppCompatActivity {

    //读取网络数据
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final TextView show = (TextView) findViewById(R.id.show);
        show.setText("loading...");
        //创建匿名类 异步任务
        new AsyncTask<Void, Void, String>() {
            @Override
            protected String doInBackground(Void... params) {
                try {
                    //InputStream的作用是标志那些从不同数据起源产生输入的类。
                    InputStream in = new URL("http://jikexueyuan.com").openStream();
                    //BufferedReader 由Reader类扩展而来,提供通用的缓冲方式文本读取,
                    //而且提供了很实用的readLine,读取一个文本行,从字符输入流中读取文本,
                    //缓冲各个字符,从而提供字符、数组和行的高效读取。
              BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8"));
                    //编码方式
                    String line = null;
                    //和String类相同,StringBuffer 和 StringBuilder 类的对象能够被多次的修改,
                    //并且不产生新的未使用对象。
                    StringBuffer content = new StringBuffer();
                    //readLine()使用起来特别方便,每次读回来的都是一行
                    while ((line = reader.readLine()) != null) {
                        //添加到数据中,把所有内容呈现在一起
                        content.append(line);
                    }
                    //关闭
                    reader.close();
                    System.out.println(content.toString());
                    return String.valueOf(content);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }

            //执行完毕后实现的函数
            protected void onPostExecute(String s) {
                super.onPostExecute(s);

                if (s != null) {
                    show.setText(s);
                }
            }
        }.execute();
    }
}

 

 

我发现再好的教程,如果你只是搜到,而不去敲一遍。永远都不会去好好写的。

转载于:https://my.oschina.net/TAOH/blog/809549

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值