Android学习篇章43-HttpClient网络通信

来源:互联网 发布:unity3d增强现实 教程 编辑:程序博客网 时间:2024/05/11 01:37

MainActivity:

public class MainActivity extends Activity {EditText  nameTxt=null;EditText  pwdTxt=null;ProgressDialog dialog=null;Handler  handler=new Handler(){@Overridepublic void handleMessage(Message msg) {//根据结果编码分别处理if(msg.what==0x201){ Userinfo user=(Userinfo) msg.getData().get("user"); Toast.makeText(MainActivity.this, "欢迎:"+user.getUsername()+" 年龄:"+user.getAge(), Toast.LENGTH_LONG).show();}else if(msg.what==0x202){Toast.makeText(MainActivity.this, "请输入正确的用户名和密码", Toast.LENGTH_LONG).show();}else if(msg.what==0x203){Toast.makeText(MainActivity.this, "网络有问题 请稍后再试", Toast.LENGTH_LONG).show();}dialog.dismiss();super.handleMessage(msg);}};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);nameTxt=(EditText)findViewById(R.id.log_name_txt);pwdTxt=(EditText)findViewById(R.id.log_pwd_txt);dialog=new ProgressDialog(this);dialog.setTitle("登陆");dialog.setMessage("访问服务器,请稍候...");dialog.setCancelable(false);dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);}public void  clickBtn(View view){ int id=view.getId(); if(R.id.btn1==id) { String name=""+nameTxt.getText(); String pwd=""+pwdTxt.getText(); new MyLoginThread(name, pwd).start(); //对话框的显示不能放在子线程中 dialog.show(); }}private class  MyLoginThread  extends Thread{String name;String pwd;public MyLoginThread(String name,String pwd){this.name=name;this.pwd=pwd;}public void run(){                 HttpClient client=new DefaultHttpClient();            //封装post请求            HttpPost  post=new HttpPost("http://192.168.1.151/myweb/login.do");    //生成请求参数列表            List<NameValuePair>  params=new ArrayList<NameValuePair>();    //生成用户名参数            BasicNameValuePair  p1=new BasicNameValuePair("username", name);    //密码参数            BasicNameValuePair  p2=new BasicNameValuePair("pwd", pwd);            params.add(p1);            params.add(p2);            HttpResponse response=null;    try {    //封装表单HttpEntity entity=new UrlEncodedFormEntity(params,"utf-8");    post.setEntity(entity);    //提交表单    response=client.execute(post);    if(response.getStatusLine().getStatusCode()==200)    {    //判断服务器状态是否处理成功  如果成功 获得响应的消息实体    HttpEntity respEntity=response.getEntity();    String str=EntityUtils.toString(respEntity);    Log.i("test", "str="+str);    if("false".equals(str.trim()))    {    Log.i("test", "aaaaaaa");    //登陆失败    handler.sendEmptyMessage(0x202);    }else     {    Log.i("test", "bbbbbbbbb");    //登陆成功    Message  msg=handler.obtainMessage();    //根据服务器端的返回  生成json对象    JSONObject  obj=new JSONObject(str);    Userinfo user=new Userinfo();    user.setUserId(obj.getInt("userId"));    user.setUsername(obj.getString("username"));    user.setPwd(obj.getString("pwd"));    user.setAge(obj.getInt("age"));    Bundle data=new Bundle();    data.putSerializable("user", user);    msg.setData(data);    msg.what=0x201;    handler.sendMessage(msg);    }    }else    {    //服务器内部错    handler.sendEmptyMessage(0x203);    }    } catch (UnsupportedEncodingException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (ClientProtocolException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (JSONException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}}

实体类:

public class Userinfo  implements Serializable{private  Integer userId;private  String  username;private  String pwd;private  Integer  age;public Integer getUserId() {return userId;}public void setUserId(Integer userId) {this.userId = userId;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPwd() {return pwd;}public void setPwd(String pwd) {this.pwd = pwd;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}}

xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    tools:context=".MainActivity" >    <TextView        android:background="#0000ff"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:gravity="center"        android:paddingTop="10dp"        android:paddingBottom="10dp"        android:textColor="#ffffff"        android:textSize="20sp"        android:text="客户端" />    <LinearLayout  android:layout_width="match_parent"           android:layout_height="wrap_content"           android:layout_marginLeft="70dp"           android:layout_marginRight="70dp"           android:layout_marginTop="10dp"           android:orientation="horizontal"           android:background="@drawable/login_input_bg"        >          <ImageView                   android:src="@drawable/icon_user"                 android:layout_width="wrap_content"                 android:layout_height="wrap_content"                />          <TextView                  android:layout_width="wrap_content"                 android:layout_height="wrap_content"                 android:textSize="15sp"                 android:text="账号:"              />          <EditText  android:id="@+id/log_name_txt"                 android:background="@null"                 android:layout_width="match_parent"                 android:layout_height="wrap_content"               />            </LinearLayout>        <LinearLayout  android:layout_width="match_parent"           android:layout_height="wrap_content"           android:layout_marginLeft="70dp"           android:layout_marginRight="70dp"           android:layout_marginTop="10dp"           android:orientation="horizontal"           android:background="@drawable/login_input_bg"        >          <ImageView                   android:src="@drawable/icon_password"                 android:layout_width="wrap_content"                 android:layout_height="wrap_content"                />          <TextView                  android:layout_width="wrap_content"                 android:layout_height="wrap_content"                 android:textSize="15sp"                 android:text="密码:"              />          <EditText  android:id="@+id/log_pwd_txt"                 android:background="@null"                 android:password="true"                 android:layout_width="match_parent"                 android:layout_height="wrap_content"               />            </LinearLayout>    <CheckBox   android:id="@+id/ck1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_marginLeft="70dp"        android:text="记住账号"        />    <CheckBox   android:id="@+id/ck2"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_marginLeft="70dp"        android:text="自动登录"        />        <Button   android:id="@+id/btn1"              style="@style/login_btn_style"              android:onClick="clickBtn"              android:text="登       录"        />    <Button   android:id="@+id/btn2"              style="@style/login_btn_style"              android:text="用户注册"        />     <Button   android:id="@+id/btn3"              style="@style/login_btn_style"              android:text="找回密码"        />    <Button   android:id="@+id/btn4"              style="@style/login_btn_style"              android:text="系统环境"        />     </LinearLayout>


权限:    <uses-permission android:name="android.permission.INTERNET"/>

原创粉丝点击