码迷,mamicode.com
首页 > 移动开发 > 详细

android 38 Abdroid客户端和服务端交互

时间:2015-10-18 16:46:53      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:

服务端:

package com.sxt.day05;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.map.ObjectMapper;

import com.sxt.day05.entity.User;

@WebServlet("/Login")
public class Login extends HttpServlet {
    private static final long serialVersionUID = 1L;
    ArrayList<User> users;
    
    public Login() {
        super();
        User user=new User("张飞", "1234", "13377889966", "zf@qq.com");
        users=new ArrayList<>();
        users.add(user);
        user=new User("王菲", "1234", "13577889966", "wf@qq.com");
        users.add(user);
        user=new User("刘亦菲", "1234", "133077889966", "lyf@qq.com");
        users.add(user);
        user=new User("咖啡", "1234", "13877889966", "kf@qq.com");
        users.add(user);
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name=request.getParameter("name");//获取客户端发过来的名字
        if(name==null){
            return ;
        }
        name=new String(name.getBytes("iso8859-1"),"utf-8");
        String pwd=request.getParameter("pwd");
        for(int i=0;i<users.size();i++){
            User user=users.get(i);
            if(name.equals(user.getName())&&pwd.equals(user.getPwd())){
                ObjectMapper om=new ObjectMapper();//jackson-core-asl.jar
                om.writeValue(response.getOutputStream(), user);//将user对象以输出流发送给客户端
                System.out.println(user.toString());
                break;
            }
        }
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ArrayList<User> list=new ArrayList<>();
        request.setCharacterEncoding("utf-8");
        String name=request.getParameter("name");
        for(int i=0;i<users.size();i++){
            User user=users.get(i);
            if(user.getName().indexOf(name)>=0){//name在user的名字中
                list.add(user);
            }
        }
        ObjectMapper om=new ObjectMapper();
        om.writeValue(response.getOutputStream(), list);
    }

}

 客户端:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" 
    android:orientation="vertical">
    <EditText 
        android:id="@+id/etName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="输入姓名"
        android:text="菲"/>
    <EditText 
        android:id="@+id/etPassword"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="输入登陆密码"
        android:text="123456"
        android:password="true"/>
    
    <Button
        android:id="@+id/btnLogin"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="GET方式登陆" />
    <Button
        android:id="@+id/btnQuery"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="POST方式查询" />
    
</LinearLayout>

客户端Activity:

package com.sxt.day06_03;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;

import org.apache.http.client.utils.URLEncodedUtils;
import org.codehaus.jackson.map.ObjectMapper;

import com.sxt.day06.entity.User;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
    private static final String PATH="http://10.0.2.2:8080/Day06_Servlet/Login_Servlet";//服务端地址
    
    EditText metName,metPwd;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        setListener();
    }

    private void setListener() {
        setLoginClickListener();
        setQueryClickListener();
    }

    private void setQueryClickListener() {//查询,POST方式
        findViewById(R.id.btnQuery).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(){//访问网络要在工作线程搞
                    public void run() {
                        String name=metName.getText().toString();
                        name="name="+name;
                        try {
                            byte[] data=name.getBytes("utf-8");
                            URL url=new URL(PATH);
                            HttpURLConnection conn=(HttpURLConnection) url.openConnection();
                            conn.setConnectTimeout(5000);
                            conn.setReadTimeout(5000);
                            conn.setRequestMethod("POST");
                            conn.setDoOutput(true);//像服务端发送数据
                            OutputStream out = conn.getOutputStream();
                            out.write(data);
                            out.flush();
                            if(conn.getResponseCode()!=200){
                                return ;
                            }
                            ObjectMapper om=new ObjectMapper();
                            List<User> users=om.readValue(conn.getInputStream(), List.class);
                            Log.i("main",users.toString());
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        } catch (MalformedURLException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    };
                }.start();
            }
        });
    }

    private void setLoginClickListener() {
        findViewById(R.id.btnLogin).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(){//访问网络要在工作线程搞
                    public void run() {
                        String name=metName.getText().toString();
                        String password=metPwd.getText().toString();
                        StringBuilder sb=new StringBuilder(PATH);//PATH地址
                        try {
                            sb.append("?name=").append(URLEncoder.encode(name, "utf-8"))
                            .append("&password=").append(password);
                            URL url=new URL(sb.toString());//
                            HttpURLConnection conn=(HttpURLConnection)url.openConnection();
                            conn.setReadTimeout(5000);//读取权限5秒,否则断开
                            conn.setConnectTimeout(5000);//连接时间5秒,否则断开
                            conn.setRequestMethod("GET");//
                            if(conn.getResponseCode()!=200){
                                Toast.makeText(MainActivity.this, "连接服务端失败", 2000).show();
                                return ;
                            }
                            ObjectMapper om=new ObjectMapper();
                            User user = om.readValue(conn.getInputStream(), User.class);
                            Log.i("main",user.toString());
                        } catch (MalformedURLException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    };
                }.start();
            }
        });
    }

    private void initView() {
        metName=(EditText) findViewById(R.id.etName);
        metPwd=(EditText) findViewById(R.id.etPassword);
    }

}

客户端项目描述文件:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.sxt.day06_03"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />
    <uses-permission android:name="android.permission.INTERNET"/>   安卓想访问网络要申请网络权限
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.sxt.day06_03.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

 

android 38 Abdroid客户端和服务端交互

标签:

原文地址:http://www.cnblogs.com/yaowen/p/4889692.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!