最近做了一個和機器人聊天的App,還沒有全部做完,我先整理出基本的功能,以後慢慢加(此版本爲1.0)。
功能:
1.實現網絡訪問
2.可以和機器人進行簡單聊天
3.在bean包中封裝了四個機器人毛毛的回答數據類
4.實現聊天記錄的存儲功能。
1.完成網絡訪問
首先需要第三方庫資源,圖靈機器人的網址:http://www.tuling123.com/ 可以設置自己的專屬機器人。
下載它的API接入文檔,裏面有詳細的請求說明,這裏不贅述。
上代碼
public static void doPost(final String massage,final HttpCallbackListner listner) {
final StringBuffer sbf = new StringBuffer();
new Thread(new Runnable() {
@Override
public void run() {
try {
URL url = new URL(API_ROBOT);
HttpURLConnection connection =
(HttpURLConnection)url.openConnection();
connection.setReadTimeout(5000);
connection.setConnectTimeout(5000);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
//規定訪問需要“utf-8"模式
connection.setRequestProperty("content-type","applcation/json: charset = utf-8");
//將發送的問題,封裝成一個javabean
SendMsg sm = new SendMsg();
sm.setKey(API_KRY);
//不用這種方式了
String Info = URLEncoder.encode(massage);
sm.setInfo(massage);
String msg =ParaseJson.convertJson(sm);
OutputStream out = connection.getOutputStream();
out.write(msg.getBytes());
out.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String str = null;
while ((str = br.readLine())!=null){
sbf.append(str);
}
str = sbf.toString();
Log.d("TAG","request message is"+str);
br.close();
out.close();
if (listner!=null){
String result = sbf.toString();
listner.onSuccess(result);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
listner.onFailed(e);
e.printStackTrace();
}
}
}).start();
2 .Json數據解析
public static Object parseJson(String result) {
List<String> list = null;
try {
JSONObject jsonobject =new JSONObject(result);
int code = jsonobject.getInt("code");
String msg = jsonobject.getString("text");
if (jsonobject.has("url")){
String url = jsonobject.getString("url");
if (jsonobject.has("list")){
JSONArray jsonArray = jsonobject.getJSONArray("list");
for (int i = 0;i<jsonArray.length();i++){
JSONObject jFather = jsonArray.getJSONObject(i);
String address = jFather.getString("detailurl");
list.add(address);
}
NewsMsg n = new NewsMsg();
n.setmCode(code);
StringBuilder sb =new StringBuilder();
sb.append(msg);
for (int k = 0; k<list.size(); k++){
sb.append(list.get(k));
}
msg = sb.toString();
n.setmMsg(msg);
return n;
}else {
LinkMsg l = new LinkMsg();
l.setUrl(url);
l.setmCode(code);
l.setmMsg(msg+url);
return l;
}
}else {
TextMsg t =new TextMsg();
t.setmMsg(msg);
t.setmCode(code);
return t;
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
3 .簡單聊天界面的實現
這部分代碼實在太多,就撿比較重要的說,這次是仿微信界面,消息的佈局分左右兩種,先創建一個CheatMessageAdapter 的類讓它繼承BaseAdapter,然後覆寫它的 getItemViewType(int position)和getViewTypeCount()方法。
@Override
public int getItemViewType(int position) {
Object object = mDates.get(position);
if (object instanceof ReturnMessage){
return 0;
}else
return 1;
}
@Override
public int getViewTypeCount() {
return 2;
}
在getView()方法裏也要進行不同判斷
@Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
Object message = mDates.get(position);
ViewHolder mHolder = null;
if (convertView ==null) {
if (getItemViewType(position) == 0) {
convertView = mInflater.inflate(R.layout.cheat_robot_layout, null);
mHolder = new ViewHolder();
mHolder.msgText = (TextView) convertView.findViewById(R.id.id_tvt_cheat_robot);
mHolder.showTimeText = (TextView) convertView.findViewById(R.id.id_tvt_timeshow);
} else {
convertView = mInflater.inflate(R.layout.cheat_me_layout, null);
mHolder = new ViewHolder();
mHolder.msgText = (TextView) convertView.findViewById(R.id.id_tvt_cheat_me);
mHolder.showTimeText = (TextView) convertView.findViewById(R.id.id_tvt_timeshow);
}
convertView.setTag(mHolder);
}else{
mHolder = (ViewHolder) convertView.getTag();
}
if (message instanceof ReturnMessage) {
setDate(mDates.get(position),mHolder);
}else if (message instanceof CheatMessage){
setDate(mDates.get(position),mHolder);
}
return convertView;
}
private final class ViewHolder{
TextView showTimeText;
TextView msgText;
}
private void setDate(Object object,ViewHolder holder) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
if (object instanceof CheatMessage) {
holder.showTimeText.setText(sdf.format(((CheatMessage) object).getDate()));
holder.msgText.setText(((CheatMessage) object).getMsg());
} else {
if (object instanceof ReturnMessage) {
switch (typeConvertNumber((ReturnMessage)object)) {
case 0:
holder.showTimeText.setText(sdf.format(new Date()));
holder.msgText.setText("出錯了,我沒有找到匹配的東西");
break;
case 1: holder.showTimeText.setText(sdf.format(new Date()));
holder.msgText.setText(((TextMsg) object).getmMsg());
break;
case 2:holder.showTimeText.setText(sdf.format(new Date()));
holder.msgText.setText(((LinkMsg) object).getmMsg());
break;
case 3:holder.showTimeText.setText(sdf.format(new Date()));
holder.msgText.setText(((NewsMsg) object).getmMsg());
}
}
}
}
private int typeConvertNumber(ReturnMessage message){
int n = 0;
if (message instanceof TextMsg){
n=1;
return n;
}else if (message instanceof LinkMsg){
n=2;
return n ;
}else if (message instanceof NewsMsg){
n =3;
return n;
}
return 0;
}
未完待續,先寫到這裏,等1.0版本寫完了,我會上傳到github上,敬請期待。