第十八天 doGet和doPost

doGet 和doPost

doGet 直接連接在url後邊 是顯式的

doPost 隱式的,比較安全

HttpUrlConnection 是sun封裝成的網絡連接

HttpClient 是apache使用HttpUrlConnection封裝的類

Encoding(JavaEE項目)

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

SQLManager(JavaEE項目)

package com.java.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class SQLManager {
    private Connection connection;
    public Connection getConnection() {
        return connection;
    }
    private static SQLManager manager;
    public static SQLManager newInstance(){
        if(manager==null){
            manager=new SQLManager();
        }
        return manager;
    }
    private SQLManager(){
        String driver="com.mysql.jdbc.Driver";
        String url="jdbc:mysql://localhost:3306/class";
        String user="root";
        String password="123456";
        try {
            Class.forName(driver);
            connection=DriverManager.getConnection(url, user, password);

        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

ServLet(JavaEE項目)

package com.java.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();  
    }
    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String userName=request.getParameter("username");
        String password=request.getParameter("password");
        userName=Encoding.doEncoing(userName);//在httpclient的dopost中,這一句不寫
        System.out.println(""+userName+","+password+"");
        String s="得到的用戶名爲:"+userName+" 密碼爲:"+password;
        Connection con=SQLManager.newInstance().getConnection();
        try {
            PreparedStatement state=con.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("登錄失敗");
            }
        } catch (SQLException e1) {
            e1.printStackTrace();
        }
        try {
            Thread.sleep(10000);
        } catch (InterruptedException 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);
    }
}

HttpUrlConnection的doGet(Java項目)

package com.java.test;
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 URLConnectionTest extends JFrame {
    private JPanel contentPane;
    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    URLConnectionTest frame = new URLConnectionTest();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    /**
     * Create the frame.
     */
    public URLConnectionTest() {
        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 btnDoget = new JButton("doGet測試");
        btnDoget.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String urlString="http://localhost:8080/JavaEE/MyTestServlet?username=zhangsan&password=123456";
                try {
                    URL url=new URL(urlString);//生成URL
                    URLConnection connection=url.openConnection();//打開URL連接
                    HttpURLConnection http=(HttpURLConnection) connection;//強制造型
                    http.setRequestMethod("GET");//設置請求方法

    //設置編碼格式                http.setRequestProperty("Accept-Charset", "utf-8");//接受的數據類型
                    http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");//設置可以接受的序列化的java對象
                    http.setConnectTimeout(3000);//請求連接的時間
                    http.setReadTimeout(3000);
                    int code=http.getResponseCode();
                    System.out.println("HTTP狀態碼"+code);
                    if(code==http.HTTP_OK){//服務器OK
                        InputStream is=http.getInputStream();
                        BufferedReader br=new BufferedReader(new InputStreamReader (is));
                        String line=br.readLine();
                        while(line!=null){
                            System.out.println(line);
                            line=br.readLine();
                        }
                    }
                }  catch(SocketTimeoutException e1){
                    System.out.println("連接超時");
                }catch(ConnectException e1){
                    System.out.println("服務器拒絕連接");
                }catch (MalformedURLException e1) {
                    e1.printStackTrace();
                }catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        });
        btnDoget.setBounds(138, 108, 102, 47);
        contentPane.add(btnDoget);
    }
}

HttpUrlConnection的doPost(Java項目)

package com.java.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.ConnectException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

public class URLConnection extends JFrame {
    private JPanel contentPane;
    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    URLConnection frame = new URLConnection();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    /**
     * Create the frame.
     */
    public URLConnection() {
        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 btnPost = new JButton("POST測試");
        btnPost.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String urlString="http://localhost:8080/JavaEE/MyTestServlet";
                try {
                    URL url=new URL(urlString);
                    HttpURLConnection http=(HttpURLConnection) url.openConnection();
                    http.setRequestProperty("Accept-Charset", "utf-8");
                    http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    http.setRequestMethod("POST");
                    http.setDoInput(true);//設置可以讀取服務器返回的內容,默認爲true
                    http.setDoOutput(true);//設置客戶端可以給服務器提交數據,默認爲false,必須設爲true
                    http.setUseCaches(false);//Post方法不允許使用緩存
                    String s="username=lisi&password=123456";
                    http.getOutputStream().write(s.getBytes());
                    http.setConnectTimeout(3000);
                    http.setReadTimeout(3000);
                    int code=http.getResponseCode();
                    System.out.println("HTTP狀態碼"+code);
                    if(code==http.HTTP_OK){
                        InputStream is=http.getInputStream();
                        BufferedReader br=new BufferedReader(new InputStreamReader (is));
                        String line=br.readLine();
                        while(line!=null){
                            System.out.println(line);
                            line=br.readLine();
                        }
                    }
                } catch(SocketTimeoutException e1){
                    System.out.println("連接超時");
                }catch(ConnectException e1){
                    System.out.println("服務器拒絕連接");
                }catch (MalformedURLException e1) {
                    e1.printStackTrace();
                }catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        });
        btnPost.setBounds(122, 107, 93, 39);
        contentPane.add(btnPost);
    }
}

HttpClient的doGet

package com.java.test;
import java.awt.EventQueue;
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.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
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.util.concurrent.TimeUnit;
import java.awt.event.ActionEvent;

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 button = new JButton("測試");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String urlString="http://localhost:8080/JavaEE/MyTestServlet?username=lisi&password=123456";
                HttpClientBuilder builder=HttpClientBuilder.create();//生成client的builder
                builder.setConnectionTimeToLive(3000, TimeUnit.MILLISECONDS);
                HttpClient client=builder.build();//生成client
                HttpGet get=new HttpGet(urlString);//設置爲get方法
                //設置服務器接收後數據的讀取方式爲utf-8
                get.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
                try {
                    HttpResponse response = client.execute(get);//執行get方法得到服務器的返回的所有數據都在response中
                    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) {
                    e1.printStackTrace();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        });
        button.setBounds(127, 110, 93, 45);
        contentPane.add(button);
    }
}

HttpClient的doPost

package com.java.test;
import java.awt.BorderLayout;
import java.awt.EventQueue;
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 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.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import java.awt.event.ActionEvent;

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 btnDopost = new JButton("DoPost");
        btnDopost.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String urlString="http://localhost:8080/JavaEE/MyTestServlet";
                HttpClientBuilder builder=HttpClientBuilder.create();
                builder.setConnectionTimeToLive(3000, TimeUnit.MILLISECONDS);
                HttpClient client=builder.build();
                HttpPost post=new HttpPost(urlString);
                NameValuePair pair1=new BasicNameValuePair("username","張三");
                NameValuePair pair2=new BasicNameValuePair("password","1234");
                ArrayList<NameValuePair> list=new ArrayList<>(); 
                list.add(pair1);
                list.add(pair2);
                try {
                    post.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
                    post.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
                    HttpResponse response=client.execute(post);
                    int code=response.getStatusLine().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 (UnsupportedEncodingException e1) {

                    e1.printStackTrace();
                } catch (ClientProtocolException e1) {
                    e1.printStackTrace();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }

            }
        });
        btnDopost.setBounds(124, 94, 124, 40);
        contentPane.add(btnDopost);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章