1.概述
1.1 将参数以json对象封装
1.2 设置请求头中的Content-type为application/json
2.以json形式发送请求需要使用json对象封装参数(这里以fastjson封装参数)
<!-- json -->
<dependency>
<groupId></groupId>
<artifactId>fastjson</artifactId>
<version>1.1.41</version>
</dependency>
请求案例代码
import ;
import ;
import ;
import ;
import ;
import ;
import ;
public class TestPostJson {
public static void main(String[] args) {
//发送json请求,对象必须封装成json格式
JSONObject params = new JSONObject();
("username","小诸葛的博客");
("password","gdupa2015");
//注意!一定要将对象转成字符串
String str = ();
sendJsonPost("/login", str);
}
/**
* @param url 发送请求的URL
* @param param 请求参数
* @return 所代表远程资源的响应结果
* @description 向指定 URL 发送POST方法的请求
* @author: liyinlong
* @date 2020-01-05 21:00
*/
public static String sendJsonPost(String url, String param) {
("\n==============================POST请求开始==============================");
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = ();
// 设置通用的请求属性
("accept", "*/*");
("connection", "Keep-Alive");
("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
//设置Content-type 为 application/json
("Content-type", "application/json");
// 发送POST请求必须设置如下两行
(true);
(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(());
// 发送请求参数
(param);
// flush输出流的缓冲
();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(()));
String line;
while ((line = ()) != null) {
result += line;
}
} catch (Exception e) {
("发送 POST 请求出现异常!" + e);
();
}
//使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
();
}
if (in != null) {
();
}
} catch (IOException ex) {
();
}
}
("url:" + url);
("POST请求结果:" + result);
("==============================POST请求结束==============================\n");
return result;
}
}
请求案例代码
import ;
import ;
import ;
import ;
import ;
import ;
public class TestGetJson {
public static void main(String[] args) {
String url = "/login?username=xiaozhuge&password=1234";
sendJsonGet(url);
}
public static String sendJsonGet(String url) {
("\n==============================POST请求开始==============================");
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = ();
// 设置通用的请求属性
("accept", "*/*");
("connection", "Keep-Alive");
("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
//设置Content-type 为 application/json
("Content-type", "application/json");
();
in = new BufferedReader(new InputStreamReader(()));
String line;
while ((line = ()) != null) {
result += line;
}
} catch (Exception e) {
("发送 POST 请求出现异常!" + e);
();
}
//使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
();
}
if (in != null) {
();
}
} catch (IOException ex) {
();
}
}
("url:" + url);
("POST请求结果:" + result);
("==============================POST请求结束==============================\n");
return result;
}
}
欢迎在评论中提出你的问题,学习愉快。
上篇:Java使用URLConnection以form形式发送POST请求