您的位置:首页 > 编程语言 > Java开发

8.12java学习篇

2015-08-12 16:00 357 查看

概况

还是关于服务器和客户端的数据解析,今天用的是HttpClient。实现的机理是,客户端与服务器交互,服务器与数据库交互。

知识点

doGet 直接连在url后边,是显示的

doPost 是隐式的,比doGet安全

服务器serverlet

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

    /**
     * @see HttpServlet#HttpServlet()
     */
    public MyServerlet() {
        super();
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //response.getWriter().append("Served at: ").append(request.getContextPath());
        String userName = request.getParameter("userName");
        String password = request.getParameter("password");
        userName = Encoding.doEncoding(userName);
        String s = "用户名:"+userName+" 密码:"+password;
        System.out.println(s);
        Connection conn = SQLManager.newInstance().getConnection();
        try {
            PreparedStatement state = conn.prepareStatement("select * from user where user_name=? and password=?");
            state.setString(1, userName);
            state.setString(2, password);
            ResultSet set = state.executeQuery();
            set.last();
            int num = set.getRow();
            if(num>=1){
                System.out.println("登录成功");
            }else{
                System.out.println("用户名或密码错误");
            }
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        response.getWriter().append(s);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

}


public class Encoding {
    public static String doEncoding(String string){
        if(string==null){
            return null;
        }
        try {
            byte[] array = string.getBytes("ISO-8859-1");
            string = new String(array,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return string;
    }
}


public class SQLManager {

    private Statement statement;
    private static SQLManager manager;
    private Connection connection;

    public Connection getConnection() {
        return connection;
    }

    public void setConnection(Connection connection) {
        this.connection = connection;
    }

    public Statement getStatement() {
        return statement;
    }

    public void setStatement(Statement statement) {
        this.statement = statement;
    }

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

    private SQLManager(){

        String driver = "com.mysql.jdbc.Driver";
        String url = "jdbc:mysql://localhost:3306/clazz";
        String user = "root";
        String password = "chuwenbin";

        try {
            Class.forName(driver);
            connection = DriverManager.getConnection(url,user,password);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}


HttpUrlConnection

客户端(doGet)

public class TestDoGet extends JFrame {

    private JPanel contentPane;

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

    /**
     * Create the frame.
     */
    public TestDoGet() {
        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);

        JButton btnNewButton = new JButton("\u6D4B\u8BD5doGet");
        btnNewButton.setBounds(115, 106, 154, 50);
        btnNewButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                String urlString = "http://localhost:8080/TestTom/MyServerlet?userName=zhangsan&password=123456";
                try {
                    URL url = new URL(urlString);
                    URLConnection connection = url.openConnection();
                    HttpURLConnection httpConnection = (HttpURLConnection)connection;
                    httpConnection.setRequestMethod("GET");
                    httpConnection.setConnectTimeout(3000);
                    //设置连接超时时间
                    httpConnection.setReadTimeout(3000);
                    //设置读取超时时间
                    httpConnection.setRequestProperty("Accept-Charset", "utf-8");
                    //设置接受的数据类型,设置编码格式
                    httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    //设置可以接受序列化的java对象
                    int code = httpConnection.getResponseCode();
                    System.out.println("HTTP状态码:"+code);
                    if(code==httpConnection.HTTP_OK){
                        InputStream is = httpConnection.getInputStream();
                        BufferedReader br = new BufferedReader(new InputStreamReader(is));
                        String line = br.readLine();
                        while(line!=null){
                            System.out.println(line);
                            line = br.readLine();
                        }
                    }
                } catch (MalformedURLException e2) {
                    e2.printStackTrace();
                } catch (SocketTimeoutException e2) {
                    System.err.println("连接超时");
                }catch (ConnectException e2) {
                    System.err.println("连接失败"); 
                }catch (IOException e2) {
                    e2.printStackTrace();
                }
            }
        });
        contentPane.add(btnNewButton);
    }
}


客户端(doPost)

public class TestDoPost extends JFrame {

    private JPanel contentPane;

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

    /**
     * Create the frame.
     */
    public TestDoPost() {
        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);

        JButton btnNewButton = new JButton("doPost");
        btnNewButton.setBounds(139, 75, 170, 64);
        btnNewButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                String urlString = "http://localhost:8080/TestTom/MyServerlet";
                try {
                    URL url = new URL(urlString);
                    URLConnection connection = url.openConnection();
                    HttpURLConnection httpConnection = (HttpURLConnection)connection;
                    httpConnection.setRequestMethod("POST");
                    httpConnection.setConnectTimeout(15000);
                    //设置连接超时时间
                    httpConnection.setReadTimeout(15000);
                    //设置读取超时时间
                    httpConnection.setRequestProperty("Accept-Charset", "utf-8");
                    //设置接受的数据类型,设置编码格式
                    httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    //设置可以接受序列化的java对象

                    httpConnection.setDoInput(true);
                    httpConnection.setDoOutput(true);
                    httpConnection.setUseCaches(false);
                    String params = "userName=张三&password=123456";
                    httpConnection.getOutputStream().write(params.getBytes());
                    int code = httpConnection.getResponseCode();
                    System.out.println("HTTP状态码:"+code);
                    if(code==httpConnection.HTTP_OK){
                        InputStream is = httpConnection.getInputStream();
                        BufferedReader br = new BufferedReader(new InputStreamReader(is));
                        String line = br.readLine();
                        while(line!=null){
                            System.out.println(line);
                            line = br.readLine();
                        }
                    }
                } catch (MalformedURLException e2) {
                    e2.printStackTrace();
                } catch (SocketTimeoutException e2) {
                    System.err.println("连接超时");
                }catch (ConnectException e2) {
                    System.err.println("连接失败"); 
                }catch (IOException e2) {
                    e2.printStackTrace();
                }
            }
        });
        contentPane.add(btnNewButton);
    }

}


HttpClient(apache)

doGet

public class HttpClientDoGet extends JFrame {

    private JPanel contentPane;

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

    /**
     * Create the frame.
     */
    public HttpClientDoGet() {
        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);

        JButton btnHttpclientdoget = new JButton("HttpClientDoGet");
        btnHttpclientdoget.setBounds(146, 87, 135, 73);
        btnHttpclientdoget.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                String urlString = "http://localhost:8080/TestTom/MyServerlet?userName=ZHANGSAN&password=123456";
                HttpClientBuilder builder = HttpClientBuilder.create();
                builder.setConnectionTimeToLive(3000, TimeUnit.MILLISECONDS);
                HttpClient client = builder.build();
                HttpGet get = new HttpGet(urlString);
                get.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
                try {
                    HttpResponse response = client.execute(get);
                    StatusLine statusLine = response.getStatusLine();
                    int code = statusLine.getStatusCode();
                    if(code==HttpURLConnection.HTTP_OK){
                        HttpEntity entity = response.getEntity();
                        InputStream is = entity.getContent();
                        BufferedReader br = new BufferedReader(new InputStreamReader(is));
                        String line = br.readLine();
                        while(line!=null){
                            System.out.println(line);
                            line = br.readLine();
                        }
                    }
                } catch (ClientProtocolException e1) {
                    e1.printStackTrace();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }

            }
        });
        contentPane.add(btnHttpclientdoget);
    }
}


doPost

用doPost作客户端时,服务器中的转码需要屏蔽掉,否则会乱码

public class HTTPClientDoPost extends JFrame {

    private JPanel contentPane;

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

    /**
     * Create the frame.
     */
    public HTTPClientDoPost() {
        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);

        JButton btnNewButton = new JButton("HttpClientDoPost");
        btnNewButton.setBounds(121, 102, 166, 63);
        btnNewButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String urlString = "http://192.168.0.65:8080/TestTom/MyServerlet";
                HttpClientBuilder builder = HttpClientBuilder.create();
                builder.setConnectionTimeToLive(3000, TimeUnit.NANOSECONDS);
                HttpClient client = builder.build();
                HttpPost post = new HttpPost(urlString);
                NameValuePair pair = new BasicNameValuePair("userName","张三");//不需要转码,这个类会自动转码
                NameValuePair pair2 = new BasicNameValuePair("password", "123456");
                ArrayList<NameValuePair> params = new ArrayList<>();
                params.add(pair);
                params.add(pair2);
                try {
                    post.setEntity(new UrlEncodedFormEntity(params,"utf8"));
                    post.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
                    HttpResponse response = client.execute(post);
                    int code = response.getStatusLine().getStatusCode();
                    if(code==200){
                        HttpEntity entity = response.getEntity();
                        InputStream is = entity.getContent();
                        BufferedReader br = new BufferedReader(new InputStreamReader(is));
                        String line = br.readLine();
                        while(line!=null){
                            System.out.println(line);
                            line = br.readLine();
                        }
                    }
                } 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();
                }
            }
        });
        contentPane.add(btnNewButton);
    }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: