Java initiates HTTP request

FH-Admin 2021-02-23 10:41:16
java initiates http request


GET and POST yes HTTP There are two common ways to do it .
GET Getting data from a specified server
POST Refers to submitting data to a specified server for processing

1.GET Method

Use GET Method , The parameters to be passed are appended to URL The address is sent to the server together .
for example :
characteristic :

  • GET Requests can be cached
  • GET The request is saved in the browser's browsing record
  • With GET Requested URL Can be saved as a browser bookmark
  • GET Request has length limit
  • GET Request is mainly used to get data

2.POST Method

Use POST Method , The parameters to be passed are in POST Information exists alone , and HTTP The request is sent to the server .
for example :
POST /submit HTTP/1.1

characteristic :

  • POST Requests cannot be cached
  • POST The request will not be saved in the browser browsing record
  • With POST Requested URL Can't save as browser bookmark
  • POST The request has no length limit

Implementation code

Next Java send out GET/POST The request is encapsulated as HttpRequest class , You can use it directly .HttpRequest The class code is as follows :

import java.util.List;
import java.util.Map;
//java project
public class HttpRequest {
* Assign to URL send out GET Method request
* @param url
* Send requested URL
* @param param
* Request parameters , Request parameter should be name1=value1&name2=value2 In the form of .
* @return URL Response result of the remote resource represented
public static String sendGet(String url, String param) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
URL realUrl = new URL(urlNameString);
// Open and URL Connection between 
URLConnection connection = realUrl.openConnection();
// Set common request properties 
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// Establish the actual connection 
// Get all response header fields 
Map<String, List<String>> map = connection.getHeaderFields();
// Traverse all response header fields 
for (String key : map.keySet()) {
System.out.println(key + "--->" + map.get(key));
// Definition BufferedReader Input stream to read URL Response 
in = new BufferedReader(new InputStreamReader(
String line;
while ((line = in.readLine()) != null) {
result += line;
} catch (Exception e) {
System.out.println(" send out GET Exception in request !" + e);
// Use finally Block to close the input stream 
finally {
try {
if (in != null) {
} catch (Exception e2) {
return result;
/**java project
* Assign to URL send out POST Method request
* @param url
* Send requested URL
* @param param
* Request parameters , Request parameter should be name1=value1&name2=value2 In the form of .
* @return Response result of the remote resource represented
public static String sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// Open and URL Connection between 
URLConnection conn = realUrl.openConnection();
// Set common request properties 
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// send out POST The request must be set to the following two lines 
// obtain URLConnection Object corresponding output stream 
out = new PrintWriter(conn.getOutputStream());
// Send request parameters 
// flush Buffering of output streams 
// Definition BufferedReader Input stream to read URL Response 
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
} catch (Exception e) {
System.out.println(" send out POST Exception in request !"+e);
// Use finally Block to close the output stream 、 Input stream 
catch(IOException ex){
return result;

Examples demonstrate

#app The routing address of "/show" That is to say ajax As defined in url Address , use POST、GET Methods can be submitted 
@app.route("/show",methods=["GET", "POST"])
def show():
# First, get the front-end input name data 
if request.method == "POST":
name = request.form.get("name")
if request.method == "GET":
name = request.args.get("name")
# establish Database Class object sql,test Name the database you want to access concrete Database Class constructor 
sql = Database("test")
# perform sql sentence Many say ,f+ String form , You can use... In a string {} Add the variable name in the form of The results are stored in result Array 
result = sql.execute(f"SELECT type FROM type WHERE name='{name}'")
except Exception as e:
return {'status':"error", 'message': "code error"}
if not len(result) == 0:
# This result, I think it can also be used as a data table , At most one result of the query ,result[0][0] Returns the first row, first column of an array 
return {'status':'success','message':result[0][0]}
return "rbq"

below We make use of POST Method to initiate a request ,Java The code is as follows :

 //java project
// Create origination http Request object
HttpRequest h = new HttpRequest();
// towards launch POST request , And pass in name Parameters
String content = h.sendPost("","name= Zhang Xinyu ");

We print out content value , Discovery is python in show() Back to json( stay Java in ,content Was identified as String type , instead of json)
 Insert picture description here
( In the process of transformation , I don't know what's wrong , Chinese shows unicode code . But in the back turn json There is no such problem after formatting )

String rotation json

Java Successfully launched Http After the request , because The return value is String type , Not the original python Function json Format . So we need to put The string type is changed to json Format , And pass The form of key-value pairs obtain message Corresponding value .
First, in the maven Introduction in jar package :


The conversion code is as follows :

JSONObject jsonObject = JSONObject.parseObject(content);

Running results :
 Insert picture description here



  1. Svg editor -- new path
  2. Detailed explanation of debounce and throttle of JavaScript function
  3. Anti shake and throttling and corresponding react hooks package
  4. C2m: the first CSDN article moved to MOOC script 5000 words, detailed painstaking development process, there are renderings and source code at the end of the article
  5. Front end, school recruitment, Taobao, guide
  6. [vue2 & G6] get started quickly
  7. Canvas from the beginning to the pig
  8. Take five minutes to standardize the code comments?
  9. Some thoughts on sass
  10. what?! You haven't filled in the award information yet
  11. How to get the interface + tsdoc needed by TS through swagger
  12. Binary tree
  13. Canvas drawing method in Web screenshot
  14. Front end docker image volume optimization (node + nginx / node + multi-stage construction)
  15. Become a big influence of technology? Coding pages quickly build personal blog
  16. Object and array deconstruction, spread operator, rest operator
  17. Analysis of Axios source code
  18. Two ways to delete useless code in project (Practical)
  19. Edit your picture with canvas
  20. Today's chat: 2-4 years to walk out of the resignation dilemma and comfort zone
  21. JS mechanism 3: stack, heap, garbage collection
  22. [grid compression evaluation] meshquan, meshopt, Draco
  23. Deep understanding of Vue modifier sync [Vue sync modifier example]
  24. WebView for front end engineers
  25. React form source code reading notes
  26. Deep thinking about modern package manager -- why do I recommend pnpm instead of NPM / yarn?
  27. On the sequence of event capture and event bubbling
  28. Help you build a systematic understanding of the front end scaffolding
  29. commander.js Principle analysis
  30. Common usage of nginx
  31. H5 jump to wechat app
  32. Front end algorithm interview must brush questions series [14]
  33. Thinking of cross end practice
  34. Vue server rendering principle analysis and introduction
  35. [KT] vscode plug in development example series (2)
  36. Design ideas of react and Vue framework
  37. JavaScript String.prototype.replaceAll 兼容性导致的问题
  38. JavaScript String.prototype.replaceAll Problems caused by compatibility
  39. 爱奇艺体育:体验Serverless极致扩缩容,资源利用率提升40%
  40. Iqiyi Sports: experience the ultimate expansion and contraction of serverless, and increase the utilization rate of resources by 40%
  41. 对前端异常window error捕获的全面总结
  42. A comprehensive summary of front end exception window error capture
  43. 成功解决Problem while trying to mount target]\“. HTTP response code is 400
  44. Problem while trying to mount target] \ ". HTTP response code is 400
  45. 放弃okhttp、httpClient,选择了这个牛逼的神仙工具!贼爽
  46. 前端面试每日 3+1 —— 第679天
  47. How to add elements at the beginning of an array in JS?
  48. Give up okhttp and httpclient and choose this awesome immortal tool! Thief Shuang
  49. Front end interview daily 3 + 1 - day 679
  50. 【2021 第一期】日常开发 26 个常见的 JavaScript 代码优化方案
  51. Daily development of 26 common JavaScript code optimization schemes
  52. 前端的字符串时间如何自动转换为后端Java的Date属性,介绍springMVC中如何解决时间转换问题
  53. How to automatically convert the front-end string time to the back-end Java date attribute, and how to solve the time conversion problem in spring MVC are introduced
  54. 前端面试常考题:JS垃圾回收机制
  55. ReactDOM.render串联渲染链路(一)
  56. 更简洁、更快速!腾讯云 Serverless 云函数创建流程再次升级!
  57. 粗涉Webpack
  58. Frequently asked questions in front end interview: JS garbage collection mechanism
  59. ReactDOM.render Serial rendering link (1)
  60. More concise and faster! Tencent cloud serverless cloud function creation process upgrade again!