day20

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);
    }

}

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我来回答你的问题。首先,广度优先搜索(BFS)是一种图搜索算法,可以用来解决一些问题,比如迷宫问题。在迷宫问题中,我们需要找到一条从起点到终点的最短路径。下面是用 Python 实现 BFS 解决迷宫问题的示例代码: ```python from collections import deque # 定义一个二维数组表示迷宫,0 表示可以走,1 表示障碍物 maze = [ [0, 1, 0, 0, 0], [0, 1, 0, 1, 0], [0, 0, 0, 0, 0], [0, 1, 1, 1, 0], [0, 0, 0, 1, 0], ] # 定义起点和终点 start = (0, 0) end = (4, 4) # 定义四个方向,上下左右 directions = [(-1, 0), (1, 0), (0, -1), (0, 1)] def bfs(maze, start, end): # 定义队列,初始时将起点加入队列 queue = deque([start]) # 定义 visited 集合,用于记录已经访问过的位置 visited = set([start]) while queue: # 取出队列中的第一个节点 node = queue.popleft() # 如果当前节点是终点,返回到达终点的最短距离 if node == end: return distance[node[0]][node[1]] # 对于当前节点,遍历它的四个方向 for direction in directions: # 计算出下一个节点的坐标 next_node = (node[0] + direction[0], node[1] + direction[1]) # 如果下一个节点不越界且没有访问过,并且可以走(maze[next_node[0]][next_node[1]] == 0),将它加入队列和 visited 集合 if 0 <= next_node[0] < len(maze) and 0 <= next_node[1] < len(maze[0]) and next_node not in visited and maze[next_node[0]][next_node[1]] == 0: queue.append(next_node) visited.add(next_node) # 如果没有找到到达终点的路径,返回 -1 return -1 # 计算每个位置到起点的最短距离 distance = [[float('inf') for _ in range(len(maze[0]))] for _ in range(len(maze))] distance[start[0]][start[1]] = 0 bfs(maze, start, end) ``` 在上面的代码中,我们首先定义了一个迷宫,然后定义了起点和终点。接着,我们定义了四个方向,上下左右。接下来,我们定义了 bfs 函数,用于实现广度优先搜索。在 bfs 函数中,我们首先定义了一个队列和 visited 集合,用于记录已经访问过的位置。然后,我们将起点加入队列和 visited 集合。接着,我们进行循环,取出队列中的第一个节点,遍历它的四个方向。如果下一个节点不越界且没有访问过,并且可以走,我们将它加入队列和 visited 集合。最后,如果没有找到到达终点的路径,返回 -1。 最后,我们计算每个位置到起点的最短距离,并调用 bfs 函数求解最短路径。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值