JAVA基础一大堆0812通过Http协议访问网络

通过Http协议访问网络

  包含两种方式:1、HttpUrlConnection;2、HttpClient

通过HttpUrlConnection访问网络

  HttpUrlConnection是由Sun公司封装好的网络连接,通过其中的Get和Post方法来获得客户端和服务器提供的数据。
  Get方法通过直接将访问语句加载url中“?”的后面来访问服务器
Post方法通过getOutputStream().write(params.getBytes())方法来访问服务器
  注意添加服务器的jar包时,jar包要放在WebContent/WEB-INF/lib包里!否则报错ClassNotFound
服务器代码

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.doEncoding(userName);//HttpClientDoPost访问时不需要转换编码格式,其余几个都需要
        String s="";
        Connection conn=SQLManager.newInstance().getConnection();
        try {
            PreparedStatement state=conn.prepareStatement("select * from user where name=? and password=?");
            state.setString(1, userName);
            state.setString(2, password);
            ResultSet set=state.executeQuery();
            set.last();
            int num=set.getRow();
            if(num==1){
                s="登录成功";
            }else{
                s="用户名或者密码错误";
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println(userName+":"+password);
        //让浏览器以UTF-8编码格式解析
        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);
    }

}

  Get方法访问服务器
  1.设置url和HttpURLConnection
  2.客户端输出
  3.客户端输入

import java.awt.BorderLayout;
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.ProtocolException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;

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

public class DoGetTest extends JFrame {

    private JPanel contentPane;

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

    /**
     * Create the frame.
     */
    public DoGetTest() {
        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.setBounds(161, 90, 93, 84);
        contentPane.add(btnDoGet);
        btnDoGet.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                String urlString="http://localhost:8080/MyServiceTest/MyTestServlet?username=zhangsan&password=123456";
                try {
                    //基本设置,设置URL连接,设置HttpURLConnection
                    URL url=new URL(urlString);//生成url
                    URLConnection connect=url.openConnection();//打开url连接
                    //强制造型成httpUrlConnection
                    HttpURLConnection httpConnection=(HttpURLConnection) connect;
                    //设置连接超时的时间
                    httpConnection.setConnectTimeout(3000);
                    //读取时间超时
                    httpConnection.setReadTimeout(3000);

                    //设置客户端输出
                    //设置编码格式
                    // 设置服务器接受的数据类型
                    httpConnection.setRequestProperty("Accept-Charset", "utf-8");
                    // 设置服务器可以接受序例化的java对象
                    httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    //设置请求方法
                    httpConnection.setRequestMethod("GET");

                    //客户端输入
                    int code=httpConnection.getResponseCode();
                    System.out.println("HTTP 状态码"+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 e1) {
                    e1.printStackTrace();
                } catch(ConnectException e1){
                    System.out.println("服务器未启动");
                } catch(SocketTimeoutException e1){
                    System.out.println("服务器连接超时");
                }catch (ProtocolException e1) {
                    e1.printStackTrace();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        });
    }
}

Post方法步骤同Get

import java.awt.BorderLayout;
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 javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;

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.setBounds(162, 87, 93, 70);
        contentPane.add(btnDoPost);
        btnDoPost.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                //基本设置部分
                //通过url来实现服务器与客户端的连接
                String urlString="http://localhost:8080/MyServiceTest/MyTestServlet";
                try {
                    URL url=new URL(urlString);
                    HttpURLConnection connection=(HttpURLConnection) url.openConnection();//强制转型
                    //HttpURLConnection进行控制
                    //设置连接超时时间
                    connection.setConnectTimeout(30000);
                    //读取超时时间
                    connection.setReadTimeout(30000);

                    //设置客户端输出
                    //设置编码格式
                    // 设置接受的数据类型
                    connection.setRequestProperty("Accept-Charset", "utf-8");
                    // 设置可以接受序例化的java对象
                    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    //设置 URL 请求的方法
                    connection.setRequestMethod("POST");
                    //设置客户端可以给服务器提交数据,默认是false的,POST时必须改成true
                    connection.setDoOutput(true);
                    //设置可以读取服务器返回的内容,默认为true,不写也可以
                    connection.setDoInput(true);
                    //post方法不允许使用缓存
                    connection.setUseCaches(false);
                    String params="username=zhangsan&password=123456";
                    connection.getOutputStream().write(params.getBytes());//客户端输出数据

                    //客户端输入部分
                    int num=connection.getResponseCode();
                    //状态码404访问不到(not found)  200正常访问(ok)  500服务器错误
                    System.out.println(num);
                    if(num==HttpURLConnection.HTTP_OK){
                        InputStream is=connection.getInputStream();
                        BufferedReader br=new BufferedReader(new InputStreamReader(is));
                        String line=br.readLine();
                        while(line!=null){
                            System.out.println(line);
                            line=br.readLine();
                        }
                    }
                } catch (MalformedURLException e1) {
                    e1.printStackTrace();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        });
    }
}

通过HttpClient访问网络

  HttpClient 是Apache使用HttpUrlConnection封装的类,用于向服务器传送数据和接收服务器的数据。使用HttpClient 也分两种传送数据的方法,一种是Get方法,一种是Post方法。
  Get方法步骤:
  1.建立client;
  2.get方法客户端输出处理
  3.接收处理服务器返回数据

import java.awt.BorderLayout;
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.util.concurrent.TimeUnit;

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;

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 btnNewButton = new JButton("New button");
        btnNewButton.setBounds(163, 193, 93, 41);
        contentPane.add(btnNewButton);
        btnNewButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
            //建立client
            String urlString="http://localhost:8080/MyServerletTest/MyServerletTest?username=zhangsan&password=123456";
            HttpClientBuilder builder=HttpClientBuilder.create();
            HttpClient client=builder.build();

            //get方法
            //设置get方法及环境
            HttpGet get=new HttpGet(urlString);
            get.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            try {
                //执行get方法法获得服务器返回的所有数据
                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();
            }
            }
        });
    }
}

  Post方法步骤:
  1.建立client
  2.设置客户端输出数据
  3.Post方法客户端输出
  4.接受处理服务端数据

import java.awt.BorderLayout;
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.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

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.StatusLine;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;

import javax.swing.JButton;

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(159, 125, 136, 64);
        contentPane.add(btnNewButton);
        btnNewButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                // 建立client
                String urlString = "http://localhost:8080/MyServerletTest/MyServerletTest";
                HttpClientBuilder builder = HttpClientBuilder.create();
                HttpClient client = builder.build();

                //设置客户端输出信息
                NameValuePair pair1=new BasicNameValuePair("username", "zhangsan");
                NameValuePair pair2=new BasicNameValuePair("password", "123456");
                ArrayList<NameValuePair> array=new ArrayList<>();
                array.add(pair2);
                array.add(pair1);

                // post方法
                // 设置post方法及环境
                HttpPost post = new HttpPost(urlString);
                try {
                    //设置传递的参数格式
                    post.setEntity(new UrlEncodedFormEntity(array, "UTF-8"));
                    post.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
                    // 执行get方法法获得服务器返回的所有数据
                    HttpResponse response = client.execute(post);

                    // 接收处理服务器返回数据
                    // 获得服务器返回的表头
                    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();
                }
            }
        });
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值