Java 发起 http 请求

FH-Admin 2021-02-23 10:40:50
java Python maven


一、GET与POST

GET和POST是HTTP的两个常用方法。
GET指从指定的服务器中获取数据
POST指提交数据给指定的服务器处理

1.GET方法

使用GET方法,需要传递的参数被附加在URL地址后面一起发送到服务器。
例如:http://192.168.0.19/submit?name=zxy&age=21
特点:

  • GET请求能够被缓存
  • GET请求会保存在浏览器的浏览记录中
  • 以GET请求的URL能够保存为浏览器书签
  • GET请求有长度限制
  • GET请求主要用以获取数据

2.POST方法

使用POST方法,需要传递的参数在POST信息中单独存在,和HTTP请求一起发送到服务器。
例如:
POST /submit HTTP/1.1
Host 121.41.111.95
name=zxy&age=21

特点:

  • POST请求不能被缓存下来
  • POST请求不会保存在浏览器浏览记录中
  • 以POST请求的URL无法保存为浏览器书签
  • POST请求没有长度限制

实现代码

下面将Java发送GET/POST请求封装成HttpRequest类,可以直接使用。HttpRequest类代码如下:

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;
//java项目www.fhadmin.org
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;
}
/**java项目www.fhadmin.org
* 向指定 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;
}
}

实例演示

#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"

下面 我们利用POST方法发起请求,Java代码如下:

 //java项目www.fhadmin.org
//创建发起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);

我们打印出content值,发现就是python中show()返回的json(在Java中,content被识别为String类型,而不是json)
在这里插入图片描述
(在转换过程中,不知道出什么问题了,中文显示了unicode编码。但在后面的转json格式后就没有这样的问题了)

字符串转json

Java成功发起Http请求后,由于返回值是String类型,而不是原本python函数中的json格式。所以我们需要将字符串类型转为json格式,并通过键值对的形式得出message对应的值
首先在maven中引入jar包:

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

转换代码如下:

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

运行结果:
在这里插入图片描述

 

版权声明
本文为[FH-Admin]所创,转载请带上原文链接,感谢
https://my.oschina.net/fhadmin/blog/4960077

  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!