当前位置:首页 > Web开发 > 正文

"张三"));//创建请求体

2024-03-31 Web开发

1.HTTP与HTTPS区别

HTTP协议默认给与80端口 

HTTPS协议默认给与443     

HTTPS相较于HTTP协议更安适一些,给与SSL+安适证书,,但是效率低

2.使用代码格局模拟HTTP请求(HTTPClient)

2.1 使用HttpClient模拟get请求

//get请求 public static void getRequest() throws IOException { //创建一个默认链接 CloseableHttpClient client= HttpClients.createDefault(); //创建一个请求 HttpGet httpGet=new HttpGet("https://www.baidu.com"); //执行请求获取响应的功效 CloseableHttpResponse response=client.execute(httpGet); //获取响应的状态码 System.out.println("处事器返回的状态码:"+response.getStatusLine().getStatusCode()); //处事器正常响应 if(response.getStatusLine().getStatusCode()==200){ //获取响应的功效 System.out.println(EntityUtils.toString(response.getEntity(),"UTF-8")); } //封锁功效东西 response.close(); //封锁连接 client.close(); }

2.2 运行功效

技术图片

2.3 模拟post请求

编写一个servlet

@WebServlet("/HttpClientServlet") public class HttpClientServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //获取数据 String username = req.getParameter("username"); System.out.println("接收的数据:"+username); resp.setContentType("text/html;charset=utf-8"); resp.getWriter().write("处事器接收到数据啦~"); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req,resp); } }

2.4 post请求

//模拟post请求 public static void postRequest()throws IOException{ //创建连接 CloseableHttpClient client=HttpClients.createDefault(); //创建请求 HttpPost post=new HttpPost("http://localhost:8080/HttpClientServlet"); //创建参数行列队伍 List<NameValuePair> pairs=new ArrayList<>(); pairs.add(new BasicNameValuePair("username","张三")); //创建请求体,封装参数 UrlEncodedFormEntity entity=new UrlEncodedFormEntity(pairs,"UTF-8"); //将请求体交给当前请求 post.setEntity(entity); //发送请求 CloseableHttpResponse response=client.execute(post); System.out.println("接收到的功效为:"+EntityUtils.toString(response.getEntity(),"UTF-8")); //封锁资源 response.close(); client.close(); } }

1.HTTP与HTTPS区别

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/web/30444.html