Http通信概述

简介: Http通信概述

在进行编码之前,我们先创建一个Servlet,该Servlet接收客户端的参数(name和age),并响应客户端。

@WebServlet(urlPatterns={"/demo.do"})
public class DemoServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String name = request.getParameter("name");
        String age = request.getParameter("age");
        PrintWriter pw = response.getWriter();
        pw.print("您使用GET方式请求该Servlet。<br />" + "name = " + name + ",age = " + age);
        pw.flush();
        pw.close();
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String name = request.getParameter("name");
        String age = request.getParameter("age");
        PrintWriter pw = response.getWriter();
        pw.print("您使用POST方式请求该Servlet。<br />" + "name = " + name + ",age = " + age);
        pw.flush();
        pw.close();
    }
}


使用JDK实现http通信


使用URLConnection实现GET请求


1、实例化一个java.net.URL对象;

2、通过URL对象的openConnection()方法得到一个java.net.URLConnection;

3、通过URLConnection对象的getInputStream()方法获得输入流;

4、读取输入流;

5、关闭资源。

public void get() throws Exception{
    URL url = new URL("http://127.0.0.1/http/demo.do?name=Jack&age=10");
    URLConnection urlConnection = url.openConnection();                                                    // 打开连接
    BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(),"utf-8")); // 获取输入流
    String line = null;
    StringBuilder sb = new StringBuilder();
    while ((line = br.readLine()) != null) {
        sb.append(line + "\n");
    }
    System.out.println(sb.toString());
}

1.png


使用HttpURLConnection实现POST请求


java.net.HttpURLConnectionjava.net.URL的子类,提供了更多的关于http的操作(getXXX 和 setXXX方法)。该类中定义了一系列的HTTP状态码:

1.png

public void post() throws IOException{
    URL url = new URL("http://127.0.0.1/http/demo.do");
    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
    httpURLConnection.setDoInput(true);
    httpURLConnection.setDoOutput(true);        // 设置该连接是可以输出的
    httpURLConnection.setRequestMethod("POST"); // 设置请求方式
    httpURLConnection.setRequestProperty("charset", "utf-8");
    PrintWriter pw = new PrintWriter(new BufferedOutputStream(httpURLConnection.getOutputStream()));
    pw.write("name=welcome");                   // 向连接中输出数据(相当于发送数据给服务器)
    pw.write("&age=14");
    pw.flush();
    pw.close();
    BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(),"utf-8"));
    String line = null;
    StringBuilder sb = new StringBuilder();
    while ((line = br.readLine()) != null) {    // 读取数据
        sb.append(line + "\n");
    }
    System.out.println(sb.toString());
}

1.png


使用httpclient进行http通信


httpclient大大简化了JDK中http通信的实现。

maven依赖:

1.<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.3.6</version>
</dependency>


GET请求


public void httpclientGet() throws Exception{
    // 创建HttpClient对象
    HttpClient client = HttpClients.createDefault();
    // 创建GET请求(在构造器中传入URL字符串即可)
    HttpGet get = new HttpGet("http://127.0.0.1/http/demo.do?name=admin&age=40");
    // 调用HttpClient对象的execute方法获得响应
    HttpResponse response = client.execute(get);
    // 调用HttpResponse对象的getEntity方法得到响应实体
    HttpEntity httpEntity = response.getEntity();
    // 使用EntityUtils工具类得到响应的字符串表示
    String result = EntityUtils.toString(httpEntity,"utf-8");
    System.out.println(result);
}


POST请求


public void httpclientPost() throws Exception{
    // 创建HttpClient对象
    HttpClient client = HttpClients.createDefault();
    // 创建POST请求
    HttpPost post = new HttpPost("http://127.0.0.1/http/demo.do");
    // 创建一个List容器,用于存放基本键值对(基本键值对即:参数名-参数值)
    List<BasicNameValuePair> parameters = new ArrayList<>();
    parameters.add(new BasicNameValuePair("name", "张三"));
    parameters.add(new BasicNameValuePair("age", "25"));
    // 向POST请求中添加消息实体
    post.setEntity(new UrlEncodedFormEntity(parameters, "utf-8"));
    // 得到响应并转化成字符串
    HttpResponse response = client.execute(post);
    HttpEntity httpEntity = response.getEntity();
    String result = EntityUtils.toString(httpEntity,"utf-8");
    System.out.println(result);
}

1.png

相关文章
|
2月前
|
缓存 安全 应用服务中间件
HTTPS解密:安全通信的魔法之窗
HTTPS解密:安全通信的魔法之窗
40 0
|
3月前
|
算法 安全 网络安全
HTTPS加密原理解析:保障通信安全的密码学算法
HTTPS加密原理解析:保障通信安全的密码学算法
52 0
|
5月前
|
安全 数据安全/隐私保护
使用openssl 模拟ca进行证书的申请和颁发,并使用证书部署网站的安全连接访问,即https的加密通信
使用openssl 模拟ca进行证书的申请和颁发,并使用证书部署网站的安全连接访问,即https的加密通信
46 0
|
8月前
|
Web App开发 网络协议 前端开发
【从零学习python 】86. 深入了解HTTP协议及其在浏览器和服务器通信中的作用
【从零学习python 】86. 深入了解HTTP协议及其在浏览器和服务器通信中的作用
87 0
|
8月前
|
编解码 移动开发 C++
初识http协议,简单实现浏览器和服务器通信
初识http协议,简单实现浏览器和服务器通信
730 0
|
9月前
|
存储 域名解析 安全
计算机网络面试专题:HTTP协议基本概念以及通信过程
计算机网络面试专题:HTTP协议基本概念以及通信过程、HTTPS基本概念、SSL加密原理、通信过程、中间人攻击问题、HTTP协议和HTTPS协议区别
66 1
|
监控 网络协议 安全
一文了解HTTP、HTTPS、TCP、UDP、Websocket(论点:概念、通信流程、异同点、应用领域)
一文了解HTTP、HTTPS、TCP、UDP、Websocket(论点:概念、通信流程、异同点、应用领域)
|
网络协议 网络安全 数据安全/隐私保护
HTTPS通信原理
大家好,我是阿萨。昨天学习了Header 常见字段学习。今天我们开始学习下HTTPs 客户端和服务器端通信原理。
115 0
HTTPS通信原理
|
Swift 数据安全/隐私保护 iOS开发
iOS开发 - swift通过Alamofire实现https通信
iOS开发 - swift通过Alamofire实现https通信
345 0
iOS开发 - swift通过Alamofire实现https通信
|
缓存 API
Qt 5——使用http协议通信
Qt 5——使用http协议通信
460 0