Java学习之路0814(httpClient与服务器实例)

Client端

/**
 * Client 界面视图
 */
import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextArea;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JPasswordField;

public class HttpClientView extends JFrame {

    private JPanel contentPane;
    private JPasswordField passwordField;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    HttpClientView frame = new HttpClientView();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public HttpClientView() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JTextArea textAreaName = new JTextArea();
        textAreaName.setBounds(128, 72, 152, 24);
        contentPane.add(textAreaName);

        passwordField = new JPasswordField();
        passwordField.setBounds(128, 125, 152, 18);
        contentPane.add(passwordField);

        JLabel label = new JLabel("用户名");
        label.setBounds(47, 76, 54, 15);
        contentPane.add(label);

        JLabel label_1 = new JLabel("密码");
        label_1.setBounds(47, 128, 54, 15);
        contentPane.add(label_1);

        JButton buttonRegister = new JButton("注册");
        buttonRegister.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String massage=HttpClientOperate.newIntance().operate(textAreaName.getText(), passwordField.getText(), "register");
                System.out.println(massage);
            }
        });
        buttonRegister.setBounds(10, 192, 93, 23);
        contentPane.add(buttonRegister);

        JButton buttonLogin = new JButton("登录");
        buttonLogin.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String massage=HttpClientOperate.newIntance().operate(textAreaName.getText(), passwordField.getText(),"login"); 
                System.out.println(massage);
            }
        });
        buttonLogin.setBounds(153, 192, 93, 23);
        contentPane.add(buttonLogin);

        JButton buttonSelect = new JButton("查询");
        buttonSelect.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String massage=HttpClientOperate.newIntance().operate(textAreaName.getText(), passwordField.getText(),"select");
                System.out.println(massage);
            }
        });
        buttonSelect.setBounds(293, 192, 93, 23);
        contentPane.add(buttonSelect);  
    }
}
/**
 * Client操作方法
 */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import javax.swing.JDialog;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;

import net.sf.json.JSONObject;

public class HttpClientOperate {
    private static HttpClientOperate clientOperate;

    private HttpClientOperate() {
    }
    public static synchronized HttpClientOperate newIntance(){
        if (clientOperate==null) {
            clientOperate=new HttpClientOperate();
        }
        return clientOperate;
    }
    public String operate(String useName,String password,String type){
        String url="http://localhost:8080/MyServersTest/MyTestServerlet";
        //直接在url后面的是dopost方法
        //HttpClientBuilder,生成器closeablehttpclient实例。
        //当一个特定的组件没有显式设置这类将 使用其默认的实现。
        //系统性能将 考虑配置的默认实现的时候usesystemproperties()方法之前调用调用build()。
        HttpClientBuilder builder=HttpClientBuilder.create();
        //设置最大长时间连接
        builder.setConnectionTimeToLive(3000, TimeUnit.MILLISECONDS);
        //生成client的builder,HttpClient此接口表示HTTP请求 只执行最基本的合同。
        HttpClient client=builder.build();//生成client方法
        //HttpPost要求源服务器接受实体 封闭在请求作为一种新的资源 请求URI请求中线确定下属
        HttpPost httpPost=new HttpPost(url);//设置为dopost方法
        JSONObject jsonObject=new JSONObject();//生成jsonobject对象
        jsonObject.put("type", type);//添加按钮事件类型
        JSONObject data=new JSONObject();//生成子jsonobject对象
        data.put("userName",useName);//添加属性key和value
        data.put("password",password);//添加属性key和value
        jsonObject.put("data", data);//添加属性key和value
        //NameValuePair将一属性与值关联,简单名称值对节点类
        NameValuePair pair=new BasicNameValuePair("json", jsonObject.toString());
        ArrayList< NameValuePair> params=new ArrayList<>();
        params.add(pair);
        try {
            //setEntity(HttpEntity entity)将此实体与请求关联
            httpPost.setEntity(new UrlEncodedFormEntity(params,"UTF-8"));//对参数进行编码
            //设置服务器接收后的数据的读取方式为utf-8;
            //setHeader(String name,String value)重写有相同name的第一个
            httpPost.setHeader("content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
            //HttpResponse  接收并解析请求消息后,服务器响应一个HTTP响应消息 。
            HttpResponse response=client.execute(httpPost);//发起dopost请求,得到服务器的返回的所有数据在response中
            //getstatusline(),获得该响应状态行,getStatusCode(),获取该响应状态码
            int code=response.getStatusLine().getStatusCode();//获取响应码
            if (code==200) {
                //读取服务器返回的消息
                //HttpEntity    一个实体可以发送或接收一个HTTP消息。getEntity()获得该消息响应的实体
                HttpEntity entity=response.getEntity();//得到数据流的实体
                BufferedReader br=new BufferedReader(new InputStreamReader(entity.getContent()));//得到输入流
                String line=br.readLine();
                //弹框设置界面,显示服务器返回的信息。
                try {
                    MyDialog dialog = new MyDialog(line);
                    dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
                    dialog.setVisible(true);
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
                //判断字符流是否为空,非空读取下一行
                while (line!=null) {
                    System.out.println(line);
                    line=br.readLine();
                }
                System.out.println(br.toString());
                return br.toString();
            }
        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (ClientProtocolException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        return null;    
    }
}
/**
 *提示框端
 */
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.FlowLayout;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class MyDialog extends JDialog {
    /**
     * Launch the application.
     */
    /**
     * Create the dialog.
     */
    private final JPanel contentPanel = new JPanel();
    public MyDialog(String line) {
        setBounds(100, 100, 415, 151);
        getContentPane().setLayout(new BorderLayout());
        contentPanel.setLayout(new FlowLayout());
        contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPanel.add(new JLabel(line));
        getContentPane().add(contentPanel, BorderLayout.CENTER);
    }

}

Server 端

/**
 * Serverlet端
 */
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

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.apache.tomcat.util.http.fileupload.ParameterParser;

import net.sf.json.JSONObject;

/**
 * Servlet implementation class MyTestServerlet
 */
@WebServlet("/MyTestServerlet")
public class MyTestServerlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public MyTestServerlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {      
        String s=ServerOperate.newIntance().operate(request);
        System.out.println("解析到了客户端的数据");
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        System.out.println(s);
        response.getWriter().append(s);
        System.out.println("\n\n");
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}
/**
 * 服务器操作端
 */
import java.sql.Connection;
import java.sql.Statement;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

public class ServerOperate {
    private static ServerOperate operate;


    private ServerOperate() {
    }

    public static synchronized ServerOperate newIntance(){
        if (operate==null) {
            operate=new ServerOperate();
        }
        return operate;
    }
    public String operate(HttpServletRequest request) {
        String json=request.getParameter("json");
        String s="";
        System.out.println("得到的数据"+json);
        JSONObject jsonObject=JSONObject.fromObject(json);          
        String type=jsonObject.getString("type");
        String dataString=jsonObject.getString("data");
        JSONObject data=jsonObject.fromObject(dataString);
        String userName=data.getString("userName");
        String password=data.getString("password");
        userName=Encoding.doEncoding(userName);
        Connection connection=SQLManager.newInstabce().getConn();
        Statement statement=SQLManager.newInstabce().getState();
        System.out.println(type+userName+password);
        if (type.equals("register")) {
            s=ServerRegister.newIntance().register(connection, statement, userName, password);
        }else if(type.equals("login")){
            s=ServerLogin.newIntance().login(connection, statement, userName, password);
        }else if(type.equals("select")){
            s=ServerSelect.newInstance().select(connection, statement, userName, password, jsonObject); 
        }
        return s;
    }


}
/**
 * 连接数据库
 */
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class SQLManager {

    public Connection conn;

    public Connection getConn() {
        return conn;
    }

    public Statement state;

    public Statement getState() {
        return state;
    }

    public void setState(Statement state) {
        this.state = state;
    }

    // 单例设计模式
    private static SQLManager manager;

    public static synchronized SQLManager newInstabce() {
        if (manager == null) {
            manager = new SQLManager();
        }
        return manager;
    }

    private SQLManager() {

        // 链接数据库驱动
        String driver = "com.mysql.jdbc.Driver";
        // URL指向要访问的数据库名
        String url = "jdbc:mysql://localhost:3306/calzz";
        // MySQL配置使得用户名
        String user = "root";
        // Java连接MySQL时配置的密码
        String password = "2012163";
        try {
            Class.forName(driver);// 加载驱动
            // 与数据库建立连接
            conn = DriverManager.getConnection(url, user, password);
            if (!conn.isClosed()) {
                // 数据库操作类
                state = conn.createStatement();
                String creatTable = "CREATE TABLE if not exists user (id int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,name varchar(20) BINARY NOT NULL,password int(6) NOT NULL )";
                state.execute(creatTable);
                System.out.println("执行成功");
            } else {
                System.out.println("请打开数据库");
            }
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}
**
 * 编码方式转换
 */
import java.io.UnsupportedEncodingException;

public class Encoding {
    public static String doEncoding(String string) {

        try {
            byte[] array = string.getBytes("ISO-8859-1");
            string = new String(array, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return string;
    }
}
/**
 * 注册方法
 */
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class ServerRegister {

    private static ServerRegister register;

    private ServerRegister() {
    }

    public static synchronized ServerRegister newIntance(){
        if (register==null) {
            register=new ServerRegister();
        }
        return register;
    }
    public String register(Connection connection,Statement statement,String userName,String password) {
        String s=null;
        try {
            if (!connection.isClosed()) {
                String select= "select *  from user where name='"+userName+"'";
                ResultSet set= statement.executeQuery(select);
                set.last();
                System.out.println(set.last());
                int num=set.getRow();
                System.out.println("num:"+num);
                if (num>0) {
                    s="该用户已注册";
                }else{
                    String insert="insert into user(name,password)values('" + userName + "','" + password
                            + "')";
                    statement.execute(insert);
                    s="注册成功!";
                }
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }   
    return s;
    }   
}
**
 * 登录方法
 */
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class ServerLogin {

    private static ServerLogin login;

    public ServerLogin() {
    }
    public static synchronized ServerLogin newIntance(){
        if (login==null) {
            login=new ServerLogin();
        }
        return login;
    }
    public String login(Connection connection,Statement statement,String userName,String password) {
        String s=null;
        try {           
            if (!connection.isClosed()) {
                String select= "select *  from user where name='"+userName+"'and password='"+password+"'";
                ResultSet set= statement.executeQuery(select);
                set.last();
                System.out.println(set.last());
                int num=set.getRow();
                System.out.println("num:"+num);
                if (num>0) {
                    s="登录成功!";
                }else{
                    s="登录失败!";
                }
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    return s;
    }
}
/**
 * 查询方法
 */
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import net.sf.json.JSONObject;

public class ServerSelect {

    private static ServerSelect select;

    public ServerSelect() {
    }
    public static synchronized ServerSelect newInstance(){
        if (select==null) {
            select=new ServerSelect();
        }
        return select;
    }
    public String select(Connection connection,Statement statement,String userName,String password,JSONObject jsonObject) {
        String s=null;
        try {       
            if (!connection.isClosed()) {
                String select= "select *  from user where name='"+userName+"'and password='"+password+"'";
                ResultSet set= statement.executeQuery(select);
                set.last();
                System.out.println(set.last());
                int num=set.getRow();
                System.out.println("num:"+num);
                String respone=null;
                if (num>0) {
                    respone="查询成功";
                    s=respone+jsonObject.toString();                        
                }else{
                    respone="查询失败!该用户不存在!";

                    jsonObject.put("code", respone);
                    jsonObject.put("num", 1);
                    s=respone;
                    System.out.println(s);
                }
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }   
    return s;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值