功能
- 健康小知识推送
- 食品营养价值查询
- 疾病查询
- 闲聊
主要是通过http请求开放平台的api,前三个使用的百度开放平台,最后一个是图灵机器人
(前三个api好像已经不提供了,不过使用方法都是一样的,还愁找不到api吗)
代码
(完整项目源代码见 https://github.com/14353350/Yuebu-Pedometer)
api配置
//图灵机器人url及key private static final String TuLingurl = "http://www.tuling123.com/openapi/api"; final String TuLingAPIkey = "您的APIkey"; //健康小知识 private static final String HealthKnowUrl = "http://apis.baidu.com/tngou/lore/news"; //共用百度开放平台的apikey final String HealthKnowKey = "您的APIkey"; //食品查询 private static final String HealthFoodUrl = "http://apis.baidu.com/tngou/food/name"; //疾病查询 private static final String IllnessUrl = "http://apis.baidu.com/tngou/disease/name";
进入聊天界面请求一条健康小知识
public void onCreate(Bundle savedInstanceState) { ... /* 健康知识分类1-12:"id":11,"name":"减肥瘦身";"id":7,"name":"私密生活";"id":5,"name":"女性保养";"id":4,"name":"男性健康";"id":6,"name":"孕婴手册";"id":13,"name":"夫妻情感";"id":8,"name":"育儿宝典";"id":3,"name":"健康饮食";"id":12,"name":"医疗护理";"id":1,"name":"老人健康";"id":2,"name":"孩子健康";"id":10,"name":"四季养生";"id":9,"name":"心里健康" */ //分类 int classify = new Random().nextInt(12)+1; //小知识id int id = new Random().nextInt(20000); String httpArg = "?classify="+classify+"&id="+id+"&rows=1"; sendRequestWithHttpConnection(HealthKnowUrl,httpArg,"GET",HealthKnowKey); ... }
请求图灵机器人、食品查询、疾病查询
@Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_send:// 点击发送 send(); break; case R.id.more_fun: //更多功能,包括食品查询,疾病查询 if(more_func.getVisibility() == View.GONE) more_func.setVisibility(View.VISIBLE); else more_func.setVisibility(View.GONE); break; case R.id.health_food: //食品查询 if(!TextUtils.isEmpty(mEditTextContent.getText())){ try{ //食品名称 String name= URLDecoder.decode(mEditTextContent.getText().toString(),"UTF-8"); String httpArg = "?name="+name; sendRequestWithHttpConnection(HealthFoodUrl,httpArg,"GET",HealthKnowKey); }catch(Exception e){ e.printStackTrace(); } } break; case R.id.illness_search://疾病查询 if(!TextUtils.isEmpty(mEditTextContent.getText())){ try{ //疾病名称 String name= URLDecoder.decode(mEditTextContent.getText().toString(),"UTF-8"); String httpArg = "?name="+name; sendRequestWithHttpConnection(IllnessUrl,httpArg,"GET",HealthKnowKey); }catch(Exception e){ e.printStackTrace(); } } break; case R.id.btn_back:// 返回按钮点击事件 finish();// 结束,实际开发中,可以返回主界面 break; } } /** * 发送消息(与图灵机器人聊天) */ private void send() { //发送内容 String contString = mEditTextContent.getText().toString(); if (contString.length() > 0) { //设置消息 ChatMsgEntity entity = new ChatMsgEntity(); //发送人 entity.setName(user_name); //日期时间 entity.setDate(getDate()); //消息内容,使用Html.fromHtml()返回Spanned类型文本,以支持html格式文本在TextView中正常显示 entity.setMessage(Html.fromHtml(contString)); //false是发送,true为收到 entity.setMsgType(false); //更新 mDataArrays.add(entity); mAdapter.notifyDataSetChanged();// 通知ListView,数据已发生改变 mEditTextContent.setText("");// 清空编辑框数据 mListView.setSelection(mListView.getCount() - 1);// 发送一条消息时,ListView显示选择最后一项 //请求图灵机器人的回复 String httpArg = "key=" + TuLingAPIkey + "&info=" + contString + "&userid=" + user_name; sendRequestWithHttpConnection(TuLingurl,httpArg,"POST",TuLingAPIkey); } }
判断网络是否连接
//判断网络是否可用 public static boolean isNetworkAvailable(Context context) { ConnectivityManager connectivity = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivity != null) { NetworkInfo info = connectivity.getActiveNetworkInfo(); if (info != null && info.isConnected()) { // 当前网络是连接的 if (info.getState() == NetworkInfo.State.CONNECTED) return true; } } return false; }
http请求
private void sendRequestWithHttpConnection(final String httpUrl,final String httpArg, final String method, final String key) { new Thread(new Runnable() { @Override public void run() { if(isNetworkAvailable(ChatActivity.this)){ try { String httpurl = null; //Get or Post if(method.equals("GET")){ httpurl = httpUrl + httpArg; }else{ httpurl = httpUrl; } Log.i("MyDebug",httpurl); connection = (HttpURLConnection) ((new URL(httpurl).openConnection())); connection.setRequestMethod(method); connection.setReadTimeout(8000); connection.setConnectTimeout(8000); // 填入apikey到HTTP header if(method.equals("GET")){ connection.setRequestProperty("apikey", key); } if(method.equals("POST")){ connection.setDoOutput(true); connection.getOutputStream().write(httpArg.getBytes("UTF-8")); } connection.connect(); //获取响应 InputStream inputStream = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder response = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { response.append(line); } Log.i("MyDebug","response: "+response); //判断消息类型 Message message = new Message(); if(httpUrl.equals(HealthKnowUrl)){ message.what = HealthKonwContent; //健康小知识 }else if(httpUrl.equals(HealthFoodUrl)){ message.what = HealthFoodContent; //食品查询 }else if(httpUrl.equals(IllnessUrl)){ message.what = IllnessContent; //疾病查询 } else{ message.what = TuLingContent; //图灵机器人 } message.obj = response.toString(); handler.sendMessage(message); } catch (Exception e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } } }else { Message message = new Message(); message.what = NO_INTERNET; //无网络连接 handler.sendMessage(message); } } }).start(); }
处理消息,解析json
private Handler handler = new Handler(){ public void handleMessage(Message message){ switch (message.what){ case TuLingContent: try{ JSONTokener jsonParser = new JSONTokener(message.obj.toString()); JSONObject reply = (JSONObject) jsonParser.nextValue(); String code = reply.getString("code");//状态码 Log.i("MyDebug","code: "+code); if(code.equals("40001")){ Toast.makeText(ChatActivity.this,"未获得key权限",Toast.LENGTH_SHORT).show(); }else if(code.equals("40002")){ Toast.makeText(ChatActivity.this,"请求内容 info 为空",Toast.LENGTH_SHORT).show(); }else if(code.equals("40004")){ Toast.makeText(ChatActivity.this,"您今天说的太多了,小悦要休息啦",Toast.LENGTH_SHORT).show(); }else if(code.equals("40007")){ Toast.makeText(ChatActivity.this,"格式异常",Toast.LENGTH_SHORT).show(); }else{ StringBuilder text = new StringBuilder(); text.append(reply.getString("text")); if(code.equals("200000")){ text.append("\n").append(reply.getString("url")); }else if(code.equals("302000")){ //新闻 JSONArray list = reply.getJSONArray("list"); for(int i = 0;i < list.length();i++){ JSONObject temp = list.getJSONObject(i); text.append("\n").append(temp.getString("article")).append(" ").append(temp.getString("detailurl")); } }else if(code.equals("308000")){ //菜谱 JSONArray list = reply.getJSONArray("list"); for(int i = 0;i < list.length();i++){ JSONObject temp = list.getJSONObject(i); text.append("\n").append(temp.getString("name")).append(": ").append(temp.getString("info")). append(temp.getString("detailurl")); } } Log.i("MyDebug","Text: "+text.toString()); //回复该消息 reply(text.toString()); } }catch (Exception e){ e.printStackTrace(); } break; case HealthKonwContent: try{ JSONTokener jsonParser = new JSONTokener(message.obj.toString()); JSONObject reply = (JSONObject) jsonParser.nextValue(); if(reply.getBoolean("status")){ JSONArray result = reply.getJSONArray("list"); JSONObject temp = result.getJSONObject(0); reply("标题: "+ temp.getString("title")+"\n\n"+temp.getString("description")); } }catch(Exception e){ e.printStackTrace(); } break; case HealthFoodContent: try{ JSONTokener jsonParser = new JSONTokener(message.obj.toString()); JSONObject reply = (JSONObject) jsonParser.nextValue(); if(reply.getBoolean("status")){ String temp = reply.getString("summary")+"详情"+reply.getString("url"); reply(temp); } }catch(Exception e){ e.printStackTrace(); } break; case IllnessContent: try{ JSONTokener jsonParser = new JSONTokener(message.obj.toString()); JSONObject reply = (JSONObject) jsonParser.nextValue(); if(reply.getBoolean("status")){ String temp = reply.getString("drugtext")+"详情"+reply.getString("url"); reply(temp); } }catch(Exception e){ e.printStackTrace(); } break; case NO_INTERNET: Toast.makeText(ChatActivity.this, "当前没有可用网络", Toast.LENGTH_SHORT).show(); break; default: break; } } };