Java 以post请求方式通过json格式调用Webservice接口
·
打算用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 {
// 创建连接
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
|
// 接收参数
// 转为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 {
// 创建连接
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();
}
|
AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。
更多推荐


所有评论(0)