Android客户端与服务端进行交互

 


第一种方式 post提交

Handler hand = new Handler() {
          public void handleMessage(Message msg) {
        //Toast.makeText(Registactivity.this, msg.obj.toString(), Toast.LENGTH_SHORT).show();
        String text=msg.obj.toString();
        if(text.equals("OK"))
        {
        enter(); 
        }else{
          Toast.makeText(Registactivity.this, "注册失败!", Toast.LENGTH_SHORT).show();
   
        }
         
          };
};


public void regist(View v)
   {
 
  Thread t = new Thread(){
@Override
public void run() {
//提交的数据需要经过url编码,英文和数字编码后不变
String path = "http://10.106.109.43:8080/Estore/AndroidRegist";
EditText name=(EditText) findViewById(R.id.usernames1);
EditText pwd=(EditText) findViewById(R.id.userpass);
names = name.getText().toString();
passwd = pwd.getText().toString();
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
User users=new User();
users.setEmail(names);
users.setActive(1);
users.setNickname("");
users.setActivecode("");
users.setPassword(passwd);
users.setRole("user");

//拼接出要提交的数据的字符串
Gson gson=new Gson();
String json=gson.toJson(users);

//添加post请求的两行属性
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", json.length() + "");

//设置打开输出流
conn.setDoOutput(true);
//拿到输出流
OutputStream os = conn.getOutputStream();
//使用输出流往服务器提交数据
os.write(json.getBytes());
if(conn.getResponseCode() == 200){
InputStream is = conn.getInputStream();
//String text = Utils.getTextFromStream(is);
//InputStream is=conn.getInputStream();
byte[] b=new byte[1024];
int len=0;
ByteArrayOutputStream bos=new ByteArrayOutputStream();
while((len=is.read(b))!=-1)
{
bos.write(b,0,len);

}
String text=new String (bos.toByteArray());
System.out.println("接收内容:"+text);
Message msg = hand.obtainMessage();
msg.obj = text;
hand.sendMessage(msg);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
t.start();

  
   }

protected void enter() {

Toast.makeText(Registactivity.this, "注册成功!", Toast.LENGTH_SHORT).show();
        Intent intent=new Intent(this, MainActivity.class);
        //intent.s
        startActivity(intent);

}

后台代码:

dopost{

ServletInputStream  in=request.getInputStream();
byte[] b=new byte[1024];
int len=0;
ByteArrayOutputStream bos=new ByteArrayOutputStream();
while((len=in.read(b))!=-1)
{
bos.write(b,0,len);

}
String text=new String (bos.toByteArray());
//System.out.println("内容Regist:"+text);

Gson gson=new Gson();
User users=gson.fromJson(text, User.class);
//System.out.println(users.toString());
             
            
        Userservices services=new UserserviceImpl();
      boolean flag=  services.adduser(users);
   if(flag)
   {
    response.getWriter().write("OK");
   
   }


}



第二种get方式


Handler hand=new Handler(){
public void handleMessage(android.os.Message msg) {

String texts=msg.obj.toString();
            if(texts.equals("OKss"))
  {
enter();
           }else if(texts.equals("Errorss")){
        Fail();
            }
};
};

    public void Login(View v)
    {
    EditText etname=(EditText) findViewById(R.id.username);
         name = etname.getText().toString();
         EditText etpwd=(EditText) findViewById(R.id.userpwd);
         pwd = etpwd.getText().toString();
    Thread t=new Thread(){
    
    @Override
    public void run() {
    String path="http://10.106.109.43:8080/Estore/AndroidLogin?name="+URLEncoder.encode(name) + "&pass=" + pwd;
    try {
URL url=new URL(path);
HttpURLConnection conn=(HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
 conn.setConnectTimeout(5000);
 conn.setReadTimeout(5000);
if(conn.getResponseCode()==200)
{
InputStream is=conn.getInputStream();
byte[] b=new byte[1024];
int len=0;
ByteArrayOutputStream bos=new ByteArrayOutputStream();
while((len=is.read(b))!=-1)
{
bos.write(b,0,len);

}
String text=new String (bos.toByteArray());
Message msg=hand.obtainMessage();
msg.obj=text;
hand.sendMessage(msg);
}

} catch (Exception e) {
e.printStackTrace();
}   
    }
    };
    t.start();
   
    }
    protected void Fail() {
// TODO Auto-generated method stub
    Toast.makeText(MainActivity.this, "密码或账号错误!", Toast.LENGTH_SHORT).show();

}


protected void enter() {
// TODO Auto-generated method stub
    Toast.makeText(MainActivity.this, "登陆成功!", Toast.LENGTH_SHORT).show();
Intent intent=new Intent(this,Listpoduct.class);
startActivity(intent);
}


后台代码:


protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String name=request.getParameter("name");
String passwd=request.getParameter("pass");
System.out.println("name"+name);
System.out.println("pass"+passwd);

User users=new User();
users.setEmail(name);
users.setPassword(passwd);
Userservices services=new UserserviceImpl();
User newuser= services.finduser(users);
if(newuser!=null)
{
response.getWriter().write("OKss");
}else{
response.getWriter().write("Errorss");
}

}


文章来源:http://blog.youkuaiyun.com/u014368040/article/details/51494424



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值