How does Java initiate an http request

Preface

In future projects, some functional modules may be written in different languages. This requires an http request to call the module. So below, I will take Java as an example to explain in detail how to initiate an http request.

1. GET and POST

GET and POST are two common methods of HTTP.
GET refers to obtaining data from the specified server
POST refers to submitting data to the specified server for processing

1.GET method

Using the GET method, the parameters that need to be passed are appended to the URL address and sent to the server.
For example: http://121.41.111.94/submit?name=zxy&age=21
Features:

  • GET requests can be cached
  • GET requests will be saved in the browser’s browsing history
  • The URL requested by GET can be saved as a browser bookmark
  • GET request has a length limit
  • GET request is mainly used to obtain data

2.POST method

Using the POST method, the parameters that need to be passed exist separately in the POST message and are sent to the server together with the HTTP request.
For example:
POST /submit HTTP/1.1
Host 121.41.111.94
name=zxy&age=21

Features:

  • POST request cannot be cached
  • POST requests will not be saved in the browser browsing history
  • The URL requested by POST cannot be saved as a browser bookmark
  • There is no length limit for POST requests

Implementation code

Next, encapsulate the GET/POST request sent by Java into the HttpRequest class, which can be used directly. The HttpRequest class code is as follows:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

public class HttpRequest {
    
    
    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url
     *            发送请求的URL
     * @param param
     *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param) {
    
    
        String result = "";
        BufferedReader in = null;
        try {
    
    
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
    
    
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
    
    
                result += line;
            }
        } catch (Exception e) {
    
    
            System.out.println("发送GET请求出现异常!" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
    
    
            try {
    
    
                if (in != null) {
    
    
                    in.close();
                }
            } catch (Exception e2) {
    
    
                e2.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param) {
    
    
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
    
    
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
    
    
                result += line;
            }
        } catch (Exception e) {
    
    
            System.out.println("发送 POST 请求出现异常!"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
    
    
            try{
    
    
                if(out!=null){
    
    
                    out.close();
                }
                if(in!=null){
    
    
                    in.close();
                }
            }
            catch(IOException ex){
    
    
                ex.printStackTrace();
            }
        }
        return result;
    }
}

Example demonstration

In the article on building the flask framework , we have written a functional module show(). The functional module is as follows:

#app的路由地址"/show"即为ajax中定义的url地址,采用POST、GET方法均可提交
@app.route("/show",methods=["GET", "POST"])
def show():
    #首先获取前端传入的name数据
    if request.method == "POST":
        name = request.form.get("name")
    if request.method == "GET":
        name = request.args.get("name")
    #创建Database类的对象sql,test为需要访问的数据库名字 具体可见Database类的构造函数
    sql = Database("test")
    try:
        #执行sql语句 多说一句,f+字符串的形式,可以在字符串里面以{}的形式加入变量名 结果保存在result数组中
        result = sql.execute(f"SELECT type FROM type WHERE name='{name}'")
    except Exception as e:
        return {
    
    'status':"error", 'message': "code error"}
    else:
        if not len(result) == 0:
            #这个result,我觉得也可以把它当成数据表,查询的结果至多一个,result[0][0]返回数组中的第一行第一列
            return {
    
    'status':'success','message':result[0][0]}
        else:
            return "rbq"
            

Below we use the POST method to initiate a request, the Java code is as follows:

   	 //创建发起http请求对象
       HttpRequest h = new HttpRequest();
       //向121.41.111.94/show发起POST请求,并传入name参数
       String content = h.sendPost("http://121.41.111.94/show","name=张新宇");
       System.out.println(content);         

We print out the content value and found that it is the json returned by show() in python (in Java, content is recognized as String type , not json)
Insert picture description here
(During the conversion process, I don’t know what went wrong, Chinese shows unicode encoding. .But after converting to json format, there is no such problem)

String to json

After Java successfully initiates the Http request, the return value is String instead of the json format in the original python function . So we need to convert the string type to json format , and get the value corresponding to the message in the form of key-value pairs . First introduce the jar package in maven:

		  <dependency>
          <groupId>com.alibaba</groupId>
          <artifactId>fastjson</artifactId>
          <version>1.2.28</version>
          </dependency>
          

The conversion code is as follows:

import com.alibaba.fastjson.JSONObject;
JSONObject jsonObject = JSONObject.parseObject(content);
System.out.println(jsonObject);
System.out.println(jsonObject.getString("message"));

operation result:
Insert picture description here

end

The above is that Java initiates an http request to call the function module written by python. When using python to write function modules, you can return data in json format. Later, when using Java to call, use tools to convert to get the required data.

Guess you like

Origin blog.csdn.net/Littleflowers/article/details/113955196