day20

本文详细介绍了HTTP请求方法GET和POST的区别,并通过代码实例展示了如何使用HttpClient实现这两种请求方法。包括代码实现、运行结果以及与传统URLConnection方式的对比。

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

doPost 隐式的,比get安全

HttpUrlConnection 是sun公司封装成的网络连接
HttpClient 是apache使用HttpUrlConnection封装的类
Android 中volley asyncHttp xutils

doGet

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 UrlFrame extends JFrame {

    private JPanel contentPane;

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

    /**
     * Create the frame.
     */
    public UrlFrame() {
        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("doGet测试");
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                String urlString = "http://localhost:8080/MyServerTestDay19/ServerLetTest?username=张三&password=321654";
                try {
                    URL url = new URL(urlString);
                    URLConnection connect = url.openConnection();//连接url
                    //强制转换
                    HttpURLConnection httpConnection = (HttpURLConnection)connect;
                    //设置请求方法
                    httpConnection.setRequestMethod("GET");
                    //设置连接超时时间
                    httpConnection.setConnectTimeout(3000);
                    //设置读取时间超时
                    httpConnection.setReadTimeout(3000);
                    //设置编码格式和可接受的数据类型
                    httpConnection.setRequestProperty("Accept-Charset", "utf-8");
                    //设置可接受的java对象
                    httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    int code = httpConnection.getResponseCode();
                    System.out.println("Http状态码:"+code);
                    if(code==HttpURLConnection.HTTP_OK){
                        InputStream in = httpConnection.getInputStream();
                        BufferedReader br = new BufferedReader(new InputStreamReader(in));
                        String line= br.readLine();
                        while(line!=null){
                            System.out.println(line);
                            line = br.readLine();
                        }
                    }
                } catch (SocketTimeoutException e){
                    System.out.println("连接超时");
                } catch (ConnectException e){
                    System.out.println("服务器拒绝连接");
                } catch (MalformedURLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } 
            }
        });
        btnNewButton.setBounds(117, 85, 181, 92);
        contentPane.add(btnNewButton);
    }
}

运行结果:
这里写图片描述
这里写图片描述
这里写图片描述

doPost

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 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, 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 arg0) {
                String urlString = "http://localhost:8080/MyServerTestDay19/ServerLetTest";
                try {
                    URL url = new URL(urlString);
                    URLConnection connect = url.openConnection();//连接url
                    //强制转换
                    HttpURLConnection httpConnection = (HttpURLConnection)connect;
                    //设置请求方法
                    httpConnection.setRequestMethod("POST");
                    //设置连接超时时间
                    httpConnection.setConnectTimeout(3000);
                    //设置读取时间超时
                    httpConnection.setReadTimeout(3000);
                    //设置编码格式和可接受的数据类型
                    httpConnection.setRequestProperty("Accept-Charset", "utf-8");
                    //设置可接受的java对象
                    httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    //设置可以读取服务器返回的内容
                    httpConnection.setDoInput(true);
                    //设置客户端可以给服务器提交数据
                    httpConnection.setDoOutput(true);
                    //post方法不允许缓存
                    httpConnection.setUseCaches(false);
                    String params = "username=zhangsan&password=654465321";
                    httpConnection.getOutputStream().write(params.getBytes());
                    int code = httpConnection.getResponseCode();
                    System.out.println("Http状态码:"+code);
                    if(code==HttpURLConnection.HTTP_OK){
                        InputStream in = httpConnection.getInputStream();
                        BufferedReader br = new BufferedReader(new InputStreamReader(in));
                        String line= br.readLine();
                        while(line!=null){
                            System.out.println(line);
                            line = br.readLine();
                        }
                    }
                } catch (SocketTimeoutException e){
                    System.out.println("连接超时");
                } catch (ConnectException e){
                    System.out.println("服务器拒绝连接");
                } catch (MalformedURLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
        btnDopost.setBounds(65, 53, 306, 150);
        contentPane.add(btnDopost);
    }

}

运行结果:
这里写图片描述
这里写图片描述
这里写图片描述

HttpClientDoGet

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.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 btnDogethttp = new JButton("doGetHttp");
        btnDogethttp.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                String urlString = "http://localhost:8080/MyServerTestDay19/ServerLetTest?username=张三&password=321654";
                HttpClientBuilder builder = HttpClientBuilder.create();
                builder.setConnectionTimeToLive(3000, TimeUnit.MILLISECONDS);
                //生成client的builder
                HttpClient client = builder.build();//生成client
                HttpGet get = new HttpGet(urlString);//设置为get方法
                get.setHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
                //设置服务器的读取方式为UTF-8

                try {
                    HttpResponse response = client.execute(get);//执行get方法得到服务器的返回的所有数据都在response中
                    StatusLine statusLine = response.getStatusLine();//httpClient访问服务器返回的表头,包含http状态码
                    int code = statusLine.getStatusCode();//得到状态码
                    if(code==HttpURLConnection.HTTP_OK){
                        HttpEntity entity = response.getEntity();//得到数据实体
                        InputStream in = entity.getContent();//得到输入流
                        BufferedReader br = new BufferedReader(new InputStreamReader(in));
                        String line = br.readLine();
                        while(line!=null){
                            System.out.println(line);
                            line = br.readLine();
                        }
                    }

                } catch (ClientProtocolException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

        });
        btnDogethttp.setBounds(62, 61, 300, 139);
        contentPane.add(btnDogethttp);
    }

}

运行结果:
这里写图片描述
这里写图片描述

HttpClientDoPost

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.xml.ws.Response;

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.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 btnNewButton = new JButton("doPostTest");
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                String url = "http://localhost:8080/MyServerTestDay19/ServerLetTest";
                HttpClientBuilder builder = HttpClientBuilder.create();
                builder.setConnectionTimeToLive(3000, TimeUnit.MILLISECONDS);
                HttpClient client = builder.build();
                HttpPost post = new HttpPost(url);
                NameValuePair pair1 = new BasicNameValuePair("username", "zhangsan");
                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");
                    HttpResponse response = client.execute(post);
                    int code = response.getStatusLine().getStatusCode();
                    if(code==200){
                        HttpEntity enity = response.getEntity();
                        InputStream in = enity.getContent();
                        BufferedReader br = new BufferedReader(new InputStreamReader(in));
                        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(184, 108, 93, 23);
        contentPane.add(btnNewButton);
    }

}

运行结果:
这里写图片描述
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值