Java 发送 post 传递json参数,php端接收json

打算用post请求发送json参数调用discuz的清除缓存的功能,但是discuz不允许使用post请求,不想改太多discuz的代码,最后只能用get请求发送,虽然没用到,还是总结下,以后会用到:

Java发送post请求:

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();
}

PHP接收java post传递的json:

// 接收参数
$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请求:

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();
}

 

发表评论