Java第二十天

来源:互联网 发布:岑村转让网络 编辑:程序博客网 时间:2024/06/05 15:36

/MyTestServlet

package com.lingzhuo.test;import java.io.IOException;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/** * Servlet implementation class MyTestServlet */@WebServlet("/MyTestServlet")public class MyTestServlet extends HttpServlet {    private static final long serialVersionUID = 1L;    /**     * @see HttpServlet#HttpServlet()     */    public MyTestServlet() {        super();        // TODO Auto-generated constructor stub    }    /**     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse     *      response)     */    protected void doGet(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {//      try {//          Thread.sleep(10000);//      } catch (InterruptedException e) {//          // TODO Auto-generated catch block//          e.printStackTrace();//      }        //浏览器按回车提交(调用doGet)url给服务器      request.getParameter("user_name")从服务器请求数据得到的是iso-8859-1编码的所以要进行编码转换        //然后打印在控制台        String userName = request.getParameter("user_name");        String password = request.getParameter("password");//      userName = Encoding.doEncodign(userName);//      password = Encoding.doEncodign(password);   //而使用httpclientdoget的时候则不需要这两句(不需要格式转换)        //通过网页输入的话网页输入会调用doGet方法  网页的编码是iso-8859-1        //所以要转换成字节存在字节数组里面在通过newString()方法将字节转换成utf-8格式的        System.out.println("用户名:" + userName);        System.out.println("密    码:" + password);        String s = "";        // 需要将jdbc的jar包放在WEB-INF下的lib目录下        Connection conn = SQLManager.newInstance().getConnection();//得到与数据库的连接  服务器与数据库之间的链接为同一条连接        try {            //预处理操作类            PreparedStatement state = conn.prepareStatement("select * from  user where user_name=? and password=?");            state.setString(1, userName);//将指定参数设置为给定 JavaString值      1是从左到右遇到的第一个通配符?            state.setString(2, password);            ResultSet set = state.executeQuery();//执行SQL查询 并返回该查询给resultSet            set.last();//最后一行            int num = set.getRow();            if (num == 1) {                s = "登陆成功";            } else {                s = "用户名或密码错误";            }        } catch (SQLException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        // 设置服务器端的输出流的编码                  Content-type为实体头           response.setHeader("Content-type", "text/html;charset=UTF-8");//设置要放在输出语句的前面  有这一句的话网页上显示的也不会是乱码的        response.getWriter().append(userName+password);//服务器将信息推送给客户端         try {            Thread.sleep(10000);        } catch (InterruptedException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        response.getWriter().append(s);//服务器将信息推送给客户端     }    //post 是吧数据写给服务端//  get是通过传递参数 传递到服务端http:............../userServlet?method=login&name=zhangsan&password=123    /**     * @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);    }}

Encoding

package com.lingzhuo.test;import java.io.UnsupportedEncodingException;public class Encoding {    public static String doEncodign(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;    }}

HTTPURLConnectionDoGet

package com.lingzhuo.test;import java.awt.BorderLayout;import java.awt.EventQueue;import javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.border.EmptyBorder;import javax.swing.JButton;import java.awt.event.ActionListener;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.net.ConnectException;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.SocketTimeoutException;import java.net.URL;import java.net.URLConnection;import java.awt.event.ActionEvent;public class HTTPURLConnectionDoGet extends JFrame {    private JPanel contentPane;    /**     * Launch the application.     */    public static void main(String[] args) {        EventQueue.invokeLater(new Runnable() {            public void run() {                try {                    HTTPURLConnectionDoGet frame = new HTTPURLConnectionDoGet();                    frame.setVisible(true);                } catch (Exception e) {                    e.printStackTrace();                }            }        });    }    //get只有一个流,参数附加在url后,大小个数有严格限制且只能是字符串。    //post的参数是通过另外的流传递的,不通过url,所以可以很大,也可以传递二进制数据,如文件的上传。     /**     * Create the frame.     */    public HTTPURLConnectionDoGet() {        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);        // HttpURLConnection doGet方法获取的只是服务器数据        JButton btnDoget = new JButton("DoGet");// 显示的        btnDoget.addActionListener(new ActionListener() {            public void actionPerformed(ActionEvent arg0) {                String urlString = "http://localhost:8080/MyServiceTest/MyTestServlet?user_name=zhangsan&password=123456";                try {                    // 生成一个URL                    URL url = new URL(urlString);// 根据String形式表示该URl对象                    URLConnection connect = url.openConnection();// 打开url连接                    // 强制类型转换成HttpURLConnection                    HttpURLConnection httpURLConnection = (HttpURLConnection) connect;//httpURLConnection 服务器得到链接需需要等十秒才想赢回来(服务器一直监听等待连接的到来)                    // 设置请求方法为Get                    httpURLConnection.setRequestMethod("GET");//开始通过服务器得到数据        运行服务器的doGet方法跳转到服务器url后直接更上要给数据库提交的内容其中开头有一个问号(传递参数)                    // 设置连接超时时间                    httpURLConnection.setConnectTimeout(3000);                    // 设置读取超时时间                    httpURLConnection.setReadTimeout(30000);                    // 设置编码格式和设置接收的数据类型                    httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");// 固定格式死记                    // 设置可以接受序列化的java对象                    httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");// 固定格式死记                    int code = httpURLConnection.getResponseCode();// 得到http状态码                    System.out.println("HTTP的状态码是:" + code);                    if (code == httpURLConnection.HTTP_OK) {                        InputStream is=httpURLConnection.getInputStream();                        BufferedReader br = new BufferedReader(                                new InputStreamReader(is));//                      BufferedReader br = new BufferedReader(//                              new InputStreamReader(is));                        String theLine = br.readLine();                        while (theLine != null) {//                          try {//                              Thread.sleep(6000);//                          } catch (InterruptedException e) {//                              // TODO Auto-generated catch block//                              e.printStackTrace();//                          }                            System.out.println(theLine);                            theLine = br.readLine();                        }                    }                } catch (MalformedURLException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }                // 捕捉连接超时异常                catch (SocketTimeoutException e) {                    System.out.println("网络连接超时");                } catch (ConnectException e) {                    System.out.println("连接出现异常");                } catch (IOException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }            }        });        btnDoget.setBounds(145, 116, 93, 67);        contentPane.add(btnDoget);    }}

HTTPURLConnectionDoPost

package com.lingzhuo.test;import java.awt.EventQueue;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import java.net.URLConnection;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.border.EmptyBorder;public class HTTPURLConnectionDoPost extends JFrame {    private JPanel contentPane;    /**     * Launch the application.     */    public static void main(String[] args) {        EventQueue.invokeLater(new Runnable() {            public void run() {                try {                    HTTPURLConnectionDoPost frame = new HTTPURLConnectionDoPost();                    frame.setVisible(true);                } catch (Exception e) {                    e.printStackTrace();                }            }        });    }    /**     * Create the frame.     */    public HTTPURLConnectionDoPost() {        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.addActionListener(new ActionListener() {            public void actionPerformed(ActionEvent arg0) {                //doPost是隐式的                String urlString="http://localhost:8080/MyServiceTest/MyTestServlet";//不含有参数    MyServiceTest为服务器                try {                    URL url = new URL(urlString);//根据String得到一个url                    URLConnection  connection=url.openConnection();//返回一个 URLConnection对象,它表示到 URL所引用的远程对象的连接。                    HttpURLConnection httpURLConnection = (HttpURLConnection)connection;//强转为HttpURLConnection//                  //设置连接超时时间//                  httpURLConnection.setConnectTimeout(30000);//                  //设置读取超时时间//                  httpURLConnection.setReadTimeout(30000);                    //设置编码格式和设置接收的数据类型                    httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");//固定格式死记                    //设置可以接受序列化的java对象                    httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");//固定格式死记                    //你提交数据给服务器 服务器在响应数据给你                    //设置请求方法                    httpURLConnection.setRequestMethod("POST");                                 //设置可以读取服务器的返回内容默认为true                    httpURLConnection.setDoInput(true);//可以不写                    //设置客户端可以给服务器提交数据,默认是false                    httpURLConnection.setDoOutput(true);                    //post方法不允许使用缓存                    httpURLConnection.setUseCaches(false);//固定的记住                    String params="user_name=zhangsan&password=1234546";//需要给服务器发送的字符串                    //通过httpURLConnection发送给服务器                    httpURLConnection.getOutputStream().write(params.getBytes()); //getoutputStream().write(里面可以使字节)   写了之后服务器(一直开着)就开始读取了                    //进入服务器    需要等上十秒才可以回到自己线程                    //httpURLConnection                    int code=httpURLConnection.getResponseCode();                    try {                        Thread.sleep(10000);                    } catch (InterruptedException e1) {                        // TODO Auto-generated catch block                        e1.printStackTrace();                    }                    System.out.println("HTTP的状态码是:"+code);                    if(code==httpURLConnection.HTTP_OK)                    {                        try {                            Thread.sleep(6000);                        } catch (InterruptedException e) {                            // TODO Auto-generated catch block                            e.printStackTrace();                        }                        InputStream is=httpURLConnection.getInputStream();                        BufferedReader br=new BufferedReader(new InputStreamReader(is));                        String line=br.readLine();                        while(line!=null)                        {                            System.out.println(line);                            line=br.readLine();                        }                    }                } catch (MalformedURLException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                } catch (IOException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                };           }        });        btnNewButton.setBounds(146, 117, 130, 76);        contentPane.add(btnNewButton);    }}

SQLManager

package com.lingzhuo.test;import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;public class SQLManager {    private Connection connection;    private static SQLManager manager;    public Connection getConnection() {        return connection;    }    public static synchronized SQLManager newInstance() {        if (manager == null) {            manager = new SQLManager();        }        return manager;    }    private SQLManager() {        {            // 连接数据库的驱动            String driver = "com.mysql.jdbc.Driver";            // url指向要访问的数据库clazz            String url = "jdbc:mysql://localhost:3306/clazz";            // mysql配置的用户名            String user = "root";            // mysql配置密码            String password = "201216328";            try {                // 加载数据库驱动                Class.forName(driver);                // 获得连接                connection = DriverManager.getConnection(url, user, password);//为了得到同一个连接  连数据库的链接也有好多条            } catch (SQLException e) {                // TODO Auto-generated catch block                e.printStackTrace();            } catch (ClassNotFoundException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }        }    }}

DoPostTest

package com.lingzhuo.test;import java.awt.BorderLayout;import java.awt.EventQueue;import javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.border.EmptyBorder;import javax.swing.JButton;import java.awt.event.ActionListener;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import java.awt.event.ActionEvent;public class DoPostTest extends JFrame {    private JPanel contentPane;    /**     * Launch the application.     */    public static void main(String[] args) {        EventQueue.invokeLater(new Runnable() {            public void run() {                try {                    DoPostTest frame = new DoPostTest();                    frame.setVisible(true);                } catch (Exception e) {                    e.printStackTrace();                }            }        });    }    /**     * Create the frame.     */    public DoPostTest() {        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        setBounds(100, 100, 784, 635);        contentPane = new JPanel();        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));        setContentPane(contentPane);        contentPane.setLayout(null);        JButton btnNewButton = new JButton("New button");        btnNewButton.addActionListener(new ActionListener() {            public void actionPerformed(ActionEvent arg0) {                String urlString = "http://localhost:8080/MyServiceTest/MyTestServlet";                try {                    URL url = new URL(urlString);                    HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();                    //设置连接超时的时间                    httpConnection.setConnectTimeout(30000);//没什么用                    //读取时间超时                    httpConnection.setReadTimeout(30000);                    //设置编码格式                    // 设置接受的数据类型                    httpConnection.setRequestProperty("Accept-Charset", "utf-8");//固定                    // 设置可以接受序列化的java对象                    httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");                    //设置请求方法                    httpConnection.setRequestMethod("POST");//                  httpConnection.setDoInput(true);//设置可以读取服务器返回的内容,默认为true                    //设置客户端可以给服务器提交数据,默认是false的。post方法必须设置为true                    httpConnection.setDoOutput(true);                    //post方法不允许使用缓存                    httpConnection.setUseCaches(false);                    String params="user_name=zhangsan&password=123456";                    httpConnection.getOutputStream().write(params.getBytes());//服务器对httpConnection优先级比较高                    System.out.println("-------------------");                    int code=httpConnection.getResponseCode();//连接反应的状态码                                   System.out.println(code);                    if(code==HttpURLConnection.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 e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                } catch (IOException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }            }        });        btnNewButton.setBounds(228, 130, 293, 278);        contentPane.add(btnNewButton);    }}

HttpClientDoGet

package com.lingzhuo.test;//需要导入httpclient  jar  以及json jarimport java.awt.EventQueue;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.util.concurrent.TimeUnit;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.border.EmptyBorder;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.StatusLine;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.HttpClient;import org.apache.http.client.fluent.Response;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.impl.client.HttpClientBuilder;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, 683, 516);        contentPane = new JPanel();        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));        setContentPane(contentPane);        contentPane.setLayout(null);        //没有使用connection        JButton btnNewButton = new JButton("HttpClientDoGet");        btnNewButton.addActionListener(new ActionListener() {            public void actionPerformed(ActionEvent e) {                String urlString="http://localhost:8080/MyServiceTest/MyTestServlet?user_name=zhangsan&password=123456";                HttpClientBuilder builder=HttpClientBuilder.create();//httpclientbuilder创建者          //创建生成client的buidler                //设置超时时间                builder.setConnectionTimeToLive(3000, TimeUnit.MILLISECONDS);                HttpClient client=builder.build();//builder生成client                HttpGet get=new HttpGet(urlString);//设置为get方法                get.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");                //设置服务器接收后数据的读取方式为utf8                try {                    System.out.println(2);                    HttpResponse response=client.execute(get);//执行get对象 跳转到服务器          得到服务器的返回的所有数据都在response中                    System.out.println("-------------");                    StatusLine statusLine=response.getStatusLine();//httpClient访问服务器返回的表头,包含http状态码                    int code=statusLine.getStatusCode();//得到状态码                    System.out.println(code);                    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) {                    // TODO Auto-generated catch block                    e1.printStackTrace();                } catch (IOException e1) {                    // TODO Auto-generated catch block                    e1.printStackTrace();                }            }        });        btnNewButton.setBounds(221, 150, 218, 169);        contentPane.add(btnNewButton);    }}

#

package com.lingzhuo.test;import java.awt.EventQueue;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.UnsupportedEncodingException;import java.util.ArrayList;import java.util.concurrent.TimeUnit;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.border.EmptyBorder;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 org.apache.http.protocol.HTTP;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, 810, 665);        contentPane = new JPanel();        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));        setContentPane(contentPane);        contentPane.setLayout(null);//不同点一:////通过get方式提交的数据有大小的限制,通常在1024字节左右。也就是说如果提交的数据很大,用get方法就可需要小心;而post方式没有数据大小的限制,理论上传送多少数据都可以。//不同点二:////通过get传递数据,实际上是将传递的数据按照”key,value”的方式跟在URL的后面来达到传送的目的的;而post传递数据是通过http请求的附件进行的,在URL中并没有明文显示。//                 1.创建HttpGet或HttpPost对象,将要请求的URL通过构造方法传入HttpGet或HttpPost对象。////                 2.使用DefaultHttpClient类的execute方法发送HTTP GET或HTTP POST请求,并返回HttpResponse对象。////                 3.通过HttpResponse接口的getEntity方法返回响应信息,并进行相应的处理。        JButton btnNewButton = new JButton("HttpClientDoPost");        btnNewButton.addActionListener(new ActionListener() {            public void actionPerformed(ActionEvent arg0) {                String url="http://192.168.0.52:8080/MyServiceTest/MyTestServlet";//隐式url                HttpClientBuilder builder=HttpClientBuilder.create();                //设置连接超时时间         ConnectionTimeToLive连接的生命周期                builder.setConnectionTimeToLive(3000, TimeUnit.MILLISECONDS);//3秒                HttpClient client=builder.build();//得到client                HttpPost post=new HttpPost(url);//设置为post方法 传入参数url                NameValuePair pair1=new BasicNameValuePair("user_name", "张三");//(String name,String value)                NameValuePair pair2=new BasicNameValuePair("password", "123456");                ArrayList<NameValuePair> params=new ArrayList<>();//数组链表                params.add(pair1);                params.add(pair2);                try {                    post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));                    post.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");                    System.out.println(2);                    HttpResponse response=client.execute(post);//client一执行就到服务器了 等服务器运行完才会回来                    System.out.println("--------------");                    int code=response.getStatusLine().getStatusCode();                    System.out.println(code);                    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 e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                } catch (ClientProtocolException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                } catch (IOException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }            }        });        btnNewButton.setBounds(193, 162, 305, 199);        contentPane.add(btnNewButton);    }}
0 0
原创粉丝点击