打算用post请求发送json参数调用discuz的清除缓存的功能,但是discuz不允许使用post请求,不想改太多discuz的代码,最后只能用get请求发送,虽然没用到,还是总结下,以后会用到:
Java发送post请求:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
URL url =
null
;
try
{
// 创建连接
url =
new
URL(
"http://liuchang/discuz2/api.php?mod=shs&method=updatecache"
);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(
true
);
conn.setDoInput(
true
);
conn.setUseCaches(
false
);
conn.setRequestMethod(
"POST"
);
conn.setRequestProperty(
"Content-type"
,
"application/x-www-form-urlencoded"
);
conn.connect();
// json参数
DataOutputStream out =
new
DataOutputStream(conn.getOutputStream());
JSONObject args =
new
JSONObject();
args.put(
"method"
,
"open"
);
out.writeBytes(args.toString());
out.flush();
out.close();
// 获取响应
BufferedReader reader =
new
BufferedReader(
new
InputStreamReader(conn.getInputStream()));
String lines;
StringBuffer sb =
new
StringBuffer();
while
((lines = reader.readLine()) !=
null
){
lines =
new
String(lines.getBytes(),
"utf-8"
);
sb.append(lines);
}
reader.close();
System.out.println(
"-----------------------------------------------------"
);
System.out.println(sb);
System.out.println(
"-----------------------------------------------------"
);
// 关闭连接
conn.disconnect();
}
catch
(Exception e) {
e.printStackTrace();
}
|
1
2
3
4
5
6
7
8
9
10
11
12
|
// 接收参数
$str
=
file_get_contents
(
"php://input"
);
// 转为json
$json
= json_decode(
$str
);
// json转array
$params
=
array
();
foreach
(
$json
as
$key
=>
$value
) {
$params
[
$key
] =
$value
;
}
print_r(params);
|
下面是我这次用到的Get请求:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
URL url =
null
;
try
{
// 创建连接
url =
new
URL(
"http://liuchang/discuz2/api.php?mod=shs&method=updatecache"
);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 获取响应
BufferedReader reader =
new
BufferedReader(
new
InputStreamReader(conn.getInputStream()));
String lines;
StringBuffer sb =
new
StringBuffer();
while
((lines = reader.readLine()) !=
null
){
lines =
new
String(lines.getBytes(),
"utf-8"
);
sb.append(lines);
}
reader.close();
System.out.println(
"-----------------------------------------------------"
);
System.out.println(sb);
System.out.println(
"-----------------------------------------------------"
);
// 关闭连接
conn.disconnect();
}
catch
(Exception e) {
e.printStackTrace();
}
|