图灵聊天机器人

来源:互联网 发布:微信第三方平台源码 编辑:程序博客网 时间:2024/04/28 05:11

原文:http://blog.csdn.net/lmj623565791/article/details/38498353#t1      

   因为一直以来对社交类App感兴趣,所以最近研究了一下图灵的智能聊天机器人。

   

   首先,在首页我们需要为listviwe中填充数据。并且,需要加载一条欢迎的数据。

   代码:

   public class MainActivity extends Activity {
    private EditText  mMsg;
    private ListView mchatlistView;
    private MyAdapter adapter;
    private List<ChatMessage> mdatas=new ArrayList<ChatMessage>();
    private Handler handler=new Handler(){
     public void handleMessage(Message msg) {
     ChatMessage from=(ChatMessage) msg.obj;
     mdatas.add(from);
     adapter.notifyDataSetChanged();
     mchatlistView.setSelection(mdatas.size()-1);
     };
    };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);//设置无标题
setContentView(R.layout.main_chatting);
   initview();
   
}
    private void initview()
    {
     mMsg=(EditText) findViewById(R.id.id_chat_msg);
     mchatlistView=(ListView) findViewById(R.id.id_chat_listView); 
     mdatas.add(new ChatMessage(Type.INPUT,"我是小貔貅,很高兴为您服务!"));
     adapter=new MyAdapter(mdatas,MainActivity.this);
     mchatlistView.setAdapter(adapter);
    } 
    
    public void sendMessage(View view)
    {
     final String message=mMsg.getText().toString().trim();
      if(TextUtils.isEmpty(mMsg.getText()))
        {
        Toast.makeText(this,"您还没有填写任何信息啦!", 0).show();
        return ;
        }
    ChatMessage to=new ChatMessage(Type.OUTPUT,message);
    to.setDate(new Date());
    mdatas.add(to);
    adapter.notifyDataSetChanged();
    mchatlistView.setSelection(mdatas.size()-1);
    mMsg.setText("");
    //关闭软键盘
    InputMethodManager imm=(InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    if(imm.isActive())
    {
     imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, InputMethodManager.HIDE_NOT_ALWAYS);
    }
      new Thread(){
      public void run()
      {
     ChatMessage from=null;
     try {
from=TulingUtils.sendmsg(message);
} catch (Exception e) {
from=new ChatMessage(Type.INPUT,"服务器挂了啦!");
/*from.setText("服务器挂了啦!");
from.setType(Type.INPUT);*/
}
     Message msg=Message.obtain();
     msg.obj=from;
     handler.sendMessage(msg);
      }
      }.start();
    }
}

    在我们发送完消息以后,是需要服务器为我们返回数据的,所以这里我们需要建一个帮助类,用于访问服务器,并返回数据。

    代码:

    //此类用于访问开放的API
public class TulingUtils {
private static String API_KEY = "534dc342ad15885dffc10d7b5f813451"; 
private static String URL = "http://www.tuling123.com/openapi/api";
private static ByteArrayOutputStream baos; 
    public static  ChatMessage sendmsg(String msg)
    {
     ChatMessage cm=new ChatMessage();
     String url=setParams(msg);
     String res=doGet(url);
     Gson gson = new Gson();
     Result result=gson.fromJson(res, Result.class);
        if(result.getCode()>4000000||result.getText()==null||result.getText()=="")
        {
         cm.setText("该功能等待开发。。。");
        }else
        {
         cm.setText(result.getText());
         cm.setDate(new Date());
         cm.setType(Type.INPUT);
        }        
return cm;    
    }
    //get方式访问网络
    private static String doGet(String url2) {    
     //创建一个Url
     URL url=null;
     HttpURLConnection conn=null;
     InputStream is=null;
try {
url=new URL(url2);
conn=(HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
int code=conn.getResponseCode();        
if(code==200)
{
baos = new ByteArrayOutputStream();
is=conn.getInputStream();
byte[] b=new byte[128];
int len=-1;
while((len=is.read(b))!=-1)
{
baos.write(b, 0, len);
}
baos.flush();
return baos.toString();
}else
{
throw new CommonException("连接服务器错误!");
}
} catch (Exception e) {
e.printStackTrace();
throw new CommonException("连接服务器错误!");
}
finally{
if(is!=null)
{
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(baos!=null)
{
try {
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
conn.disconnect();
}
}
//拼接URL
private static String setParams(String msg) {
try {
msg=URLEncoder.encode(msg,"UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
return URL+"?key="+API_KEY+"&info="+msg;
}
}

0 0
原创粉丝点击