网络员工管理系统学习总结

来源:互联网 发布:bilibili官方下载mac 编辑:程序博客网 时间:2024/04/28 09:35
1.URL

    符合Url的字符串由以下三部分组成:
    1).网络协议的类型  2).主机ip加端口 3).服务器上的具体资源路径
         String path = "http://localhost:8080/MyServer/index.html";
         URL url = new URL(path);
         
            String authority = url.getAuthority();
        int port = url.getPort();
        String host = url.getHost();
        String path1 = url.getPath();
        String protocol = url.getProtocol();
        
    可以通过URL获得输入流将URL指向的文件资源复制到本地:
    public class TestURL3 {
    public static void main(String[] args) {
        
        InputStream is=null;
        OutputStream os=null;
        try {
            URL url = new URL("http://localhost:8080/MyServer/index.html");
            is = url.openStream();
            File file = new File(url.getFile());
            String fileName = file.getName();
            System.out.println(fileName);
            os = new FileOutputStream("c:/1"+file.separator+fileName);
            byte[] buffer = new byte[1024];
            int len=0;
            while((len=is.read(buffer))!=-1){
                os.write(buffer, 0, len);
            }
            System.out.println("下载完成");    
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            if(is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(os!=null){
                try {
                    os.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }        
    }    
}

2.HttpURLConnection
传输方式有以下两种:
    --POST(向服务区提交数据) 传输的数据量相对较多,传输的数据安全性相对较高,如果需向服务器提交数据,则用此方式。
          需设置请求头的长度、类型(非必须)等:
      connection.setRequestMethod("POST");
            connection.setConnectTimeout(5000);
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("Content-Length", String.valueOf(datas.length));   
          
    --GET(仅从服务器端返回数据) 传输的数据量相对较小,向服务器提交的数据以在URL后追加?name=value&name=value的形式发送给服务器,
                                                                        传输的数据安全性相对较低,如果只从服务器取数据,不向服务器提交数据,可以适用,

服务器响应请求的结果,获得结果后,先通过判断响应码是不是为200, 如果是200则响应成功,如果不是则响应失败
HttpURLConnection方式下为:int statusCode = connection.getResponseCode();
HttpClient方式下为:int statusCode = response.getStatusLine().getStatusCode();


3.HttpClient 第三方框架
 -- HttpGet 相当于HttpUrlConnection的GET方式
 -- HttpPost 相当于HttpURLConnection的POST方式
 -- HttpResponse 服务器响应请求的结果,获得结果后,先通过判断响应码是不是为200,
             如果是200则响应成功,如果不是则响应失败

4.登录
  --验证码的获取
   --Cookie服务器端利用session机制保存在客户端的32位16进制数
   
 HttpClient方式下:  SESSIONID=response.getFirstHeader("Set-Cookie").getValue().split(";")[0];
 HttpUrlConnection方式下:SESSIONID=connection.getHeaderField("Set-Cookie").split(";")[0];
 
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++   
   public static String SESSIONID="";//保存服务端写在 客户端的cookie(会话编号)
    public static Bitmap getVrifyCodeBitmap(String path){
        Bitmap bitmap = null;
        try {
            URL url = new URL(path);
    
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5000);
            connection.setDoInput(true);
            int statusCode = connection.getResponseCode();
            if(statusCode==200){
                SESSIONID=connection.getHeaderField("Set-Cookie").split(";")[0];
                Log.i("TAG", "SESSIONID="+SESSIONID);
                InputStream in = connection.getInputStream();
                byte[] datas = StreamUtil.getBytesFromStream(in);
                bitmap = BitmapFactory.decodeByteArray(datas, 0, datas.length);
            }
        } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
        }
        return bitmap;
    }
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++   
  --登录
   --发送登录请求带着服务器写在客户端的cookie以及验证码(用户)  
   
       public static boolean loginHttpPost(String loginname,String password,String code,String path){
        boolean flag = false;
        Map<String,String> params = new HashMap<String,String>();
        params.put("loginname", loginname);
        params.put("password", password);
        params.put("code", code);
        StringBuilder builder =new StringBuilder();
        for(Map.Entry<String, String> entry:params.entrySet()){
            builder.append(entry.getKey());
            builder.append("=");
            builder.append(entry.getValue());
            builder.append("&");            
        }
        String strBuiler=builder.deleteCharAt(builder.length()-1).toString();
        byte[] datas = strBuiler.getBytes();
        try {
            URL url= new URL(path);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoInput(true);
            connection.setDoInput(true);
            connection.setRequestProperty("Content-Lenght", String.valueOf(datas.length));
            connection.setReadTimeout(5000);
            connection.setRequestProperty("Cookie",SESSIONID);
            
            OutputStream out =connection.getOutputStream();
            out.write(datas);
            out.flush();
            out.close();
            
            int statusCode=connection.getResponseCode();
            if(statusCode==200){
                InputStream in = connection.getInputStream();
                String jsonStr =StreamUtil.getJsonStrFromStream(in);
                try {
                    JSONObject jsonObject = new JSONObject(jsonStr);
                    String result= jsonObject.getString("result");
                    if("ok".equals(result)){
                        flag=true;
                    }else{
                        flag=false;
                        Log.i("TAG", jsonObject.getString("msg"));
                    }
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }else{
                Log.i("TAG", String.valueOf(statusCode));
            }
            
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    
        return flag;
    }
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    public static boolean loginHttpClient(String loginName,String password,String code,String path){
        boolean flag = false;
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(path);
        post.setHeader("Cookie",SESSIONID);
        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        pairs.add(new BasicNameValuePair("loginname", loginName));
        pairs.add(new BasicNameValuePair("password", password));
        pairs.add(new BasicNameValuePair("code", code));
        try {
            HttpEntity entity = new UrlEncodedFormEntity(pairs);
            post.setEntity(entity);
            HttpResponse response=client.execute(post);
            int statusCode = response.getStatusLine().getStatusCode();
            if(statusCode==200){
                HttpEntity resEntity = response.getEntity();
                String strJson = EntityUtils.toString(resEntity);
                JSONObject jsonObject = new JSONObject(strJson);
                String result = jsonObject.getString("result");
                if("ok".equals(result)){
                    flag=true;
                }else{
                    flag=false;
                    Log.i("TAG", jsonObject.getString("msg"));
                }
            }else{
                Log.i("TAG", String.valueOf(statusCode));
            }
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return flag;
    }

++++++++++++++++++++++++++++++++++++++
5.注册
  --把封装好的账户数据拼接成字符串,转成字节数组,通过输出流写到服务器端
 
  public class HttpRegist {

    public static boolean registHttpPost(User user,String path){
        boolean flag = false;
        BufferedReader reader = null;
        Map<String, String> params = new HashMap<String, String>();
        params.put("loginname", user.getLoginname());
        params.put("password", user.getPassword());
        params.put("realname", user.getRealname());
        params.put("email", user.getEmail());
        StringBuilder builder = new StringBuilder();
        for(Map.Entry<String, String> entry:params.entrySet()){
            builder.append(entry.getKey());
            builder.append("=");
            builder.append(entry.getValue());
            builder.append("&");
        }
        String strBuider = builder.deleteCharAt(builder.length()-1).toString();
        byte[] datas = strBuider.getBytes();
        try {
            URL url = new URL(path);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setConnectTimeout(5000);
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Length", String.valueOf(datas.length));
            OutputStream out = connection.getOutputStream();
            out.write(datas);
            out.flush();
            out.close();
            
            int statusCode = connection.getResponseCode();
            if(statusCode==200){
                InputStream in =connection.getInputStream();
                String jsonStr = StreamUtil.getJsonStrFromStream(in);
                try {
                    JSONObject jsonObject = new JSONObject(jsonStr);
                    String result = jsonObject.getString("result");
                    if("ok".equals(result)){
                        flag=true;
                    }else{
                        flag=false;
                        String msg = jsonObject.getString("msg");
                        Log.i("TAG", msg);
                    }
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }    
            }else{
                Log.i("TAG", "statusCode="+statusCode);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            if(reader!=null){
                try {
                    reader.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        return flag;
    }
 
      public static boolean registHttpClient(User user,String path){
        boolean flag = false;
        
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(path);
        List<NameValuePair> paires = new ArrayList<NameValuePair>();
        NameValuePair pair1 = new BasicNameValuePair("loginname", user.getLoginname());
        NameValuePair pair2 = new BasicNameValuePair("password", user.getPassword());
        NameValuePair pair3 = new BasicNameValuePair("realname", user.getRealname());
        NameValuePair pair4 = new BasicNameValuePair("email", user.getEmail());
        paires.add(pair1);
        paires.add(pair2);
        paires.add(pair3);
        paires.add(pair4);
    
        try {
            HttpEntity entity = new UrlEncodedFormEntity(paires);
            post.setEntity(entity);
            HttpResponse response = client.execute(post);
            int statusCode = response.getStatusLine().getStatusCode();
            if(statusCode==200){
                HttpEntity resultEntity = response.getEntity();
                String jsonStr = EntityUtils.toString(resultEntity);
                try {
                    JSONObject jsonObject = new JSONObject(jsonStr);
                    String result = jsonObject.getString("result");
                    if("ok".equals(result)){
                        flag = true;
                    }else {
                        flag = false;
                        Log.i("TAG", jsonObject.getString("msg"));
                    }
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }else{
                Log.i("TAG", String.valueOf(statusCode));
            }
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return flag;
    }
++++++++++++++++++++++++++++++++++++++++++++++++
6.添加员工信息
  --方式同注册
 
7.浏览所有的员工信息
  --不需要向服务器端提交任何数据
            所以发送GET请求得到相应json数据,按照json结构做数据解析
    先判断是否正确响应,响应正确后,通过“data”关键字获得JASONArray,
    再循环获得JASONArray里的每一个JASONObject的数据封装成Empolyee对象
            
    public static List<Employee> loadEmployeesHttpGet(String path){
        List<Employee> list = new ArrayList<Employee>();
        try {
            URL url = new URL(path);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5000);
            int statusCode = connection.getResponseCode();
            if(statusCode==200){
                InputStream in = connection.getInputStream();
                String jsonStr = StreamUtil.getJsonStrFromStream(in);
                JSONObject jsonObject = new JSONObject(jsonStr);
                String result = jsonObject.getString("result");
                if("ok".equals(result)){
                    JSONArray array = jsonObject.getJSONArray("data");
                    for(int i=0; i<array.length();i++){
                        JSONObject jsonEmployee = array.getJSONObject(i);

                        int id =jsonEmployee.getInt("id");
                        String name = jsonEmployee.getString("name");
                        double salary = jsonEmployee.getDouble("salary");
                        String gender =jsonEmployee.getString("gender");
                        int age = jsonEmployee.getInt("age");

                        Employee employee = new Employee(id,name,salary,age,gender);
                        list.add(employee);
                    }
                }else{
//                    Log.i("TAG", jsonObject.getString("msg"));
                }
            }else{
//                Log.i("TAG", String.valueOf(statusCode));
            }
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return list;
    }
+++++++++++++++++++++++++++++++++++++++++++++++++            

8.所有的网络访问都需要做异步处理,即需要在工作线程里进行

9.所有的网路访问都要在清单配置文件中声明相应的网络访问权限
0 0