1.grails开发的项目要与第三方项目实现某些数据的互相传递,也就是开发个webservice接口,供别的系统调用。
2.选择restful是因为业务逻辑简单,大体上你就是CRUD,如果业务比较复杂,例如转账啊什么的这个就有点够呛了。
3.服务端::创建controller 继承 RestfulController
class TestController extends RestfulController{
static responseFormats = ['json', 'xml']//传递是JSON格式数据
TestController(){
super();
}
def testMethod{
String jsonString = request.getJSON().toString();//得到传递过来json格式的字符串数据
JSONObject result = new JSONObject();
if(!jsonString.isEmpty()){
//得到数据想干什么干什么
result.put("message","success")
}else{
result.put("message","fail")
}
respond(result)//返回信息
}
}
4.客户端
public class TestResul{
public static HttpUrlUtil httpUrlUtil=HttpUrlUtil.instance();//HttpUrlUtil 是个工具包
public static void main(String[] args) {
JSONObject params=new JSONObject();
params.put("id", 0);
params.put("name", “张三”);
String result=httpUrlUtil.sendPost(path, params.toString());
System.out.println(result);
}
}
5.HttpUrlUtil 工具包代码:
public class HttpUrlUtil {
private static HttpUrlUtil httpUrlUtil=null;
public static HttpUrlUtil instance(){
if(httpUrlUtil==null){
httpUrlUtil=new HttpUrlUtil();
}
return httpUrlUtil;
}
/**
*
*JSON
* @param url
* @param params
* @return
*/
public String sendPost(String path ,String params){
StringBuffer result=new StringBuffer("");
HttpURLConnection conn =null;
DataOutputStream out=null;
OutputStreamWriter ow=null;
BufferedReader reader =null;
try {
URL url=new URL(path);
try {
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setUseCaches(false);
conn.setInstanceFollowRedirects(true);
//设置传递JSON属性
conn.setRequestProperty("Content-Type", "application/json");
conn.connect();
out = new DataOutputStream(conn.getOutputStream());
ow=new OutputStreamWriter(out,"UTF-8");//字节输出流转换成字符输出流并指定字符编码
ow.write(params);
ow.flush();
// 接受 返回数据
reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(out!=null){
out.close();
}
if(ow!=null){
ow.close();
}
if(reader!=null){
reader.close();
}
if(conn!=null){
conn.disconnect();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result.toString();
}
}
6.水平有限,仅供参考,给自己留个笔记!!!!