A p8-level character in Ali teaches you the complete step record of Java initiating an http request

This article mainly introduces you to relevant information about Java initiating http requests. The article introduces in detail through the sample code, which has a certain reference learning value for everyone's study or work. Friends who need it, follow the editor below. Learn to learn

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 means to get data from the specified server

  • POST refers to submitting data to the designated server for processing

1. The GET method
uses the GET method, and 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
  • The GET request 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. The POST method
uses the POST method, and the parameters that need to be passed exist separately in the POST message and are sent to the server together with the HTTP request.

E.g:

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 limitation
    for POST request. The implementation code
    below encapsulates 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 flask framework, we have written a function module show(). The function 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](http://121.41.111.94/show)"``,``"name=张新宇"``);`

`System.out.println(content);  `

We print out the content value and find 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 the conversion 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:

The end of 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.

So far, this article on the complete step record of Java initiating an http request is introduced. For more related content of Java initiating an http request, please pay attention to the previous article of the editor or add wx1411943564 remarks (csdn). I hope you will support the editor a lot in the future. !

Guess you like

Origin blog.csdn.net/dcj19980805/article/details/115280422