用SSH框架写了一个微信项目,因为要和别的项目对接
接口,本来想用Web
Service来实现,后来看到别的框架里面直接通过Actio来实现对接,所以就想到了用Action作为接口来实现WebService功能,通过
HTTP来调用。代码如下。
Action代码:
public String testService() throws IOException, ClassNotFoundException{
//创建request和response对象
Http
ServletResponse response = ServletActionContext.getResponse();
HttpServletRequest request=ServletActionContext.getRequest();
//设置response
编码
response.setContentType("text/html;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
//创建writer实例
PrintWriter out = null;
out = response.getWriter();
//gson 用于把map转为
JSON
Gson gs = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
//通过request获取传过来的参数,然后
解析数据流获取参数
int length = (int) request.getContentLength();// 获取长度
InputStream is = request.getInputStream();
if (length != -1) {
byte[] data = new byte[length];
byte[] temp = new byte[512];
int readLen = 0;
int destPos = 0;
while ((readLen = is.read(temp)) > 0) {
System.arraycopy(temp, 0, data, destPos, readLen);
destPos += readLen;
}
//获取的参数
String result = new String(data, "UTF-8"); // utf-8编码
System.out.println(result);
}
//把要返回的参数写入map,转成
JSON
Map map = new HashMap();
map.put("ID","123");
map.put("success", "true");
String jsonmap = gs.toJson(map);
out.print(jsonmap);
return null;
}
通过HTTP调用的代码:
public static void main(String[] args)
throws IOException, JSONException
{
//实例gson用于转换
Gson gs = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
//参数
Map map = new HashMap();
map.put("ID", "123123");
String jsonmap = gs.toJson(map);
String str = null;
//通过HTTPPost方式
try {
str = HttpsPost.send("http://localhost:8080/wx_manager/weixin/business_testService.do", "POST", jsonmap);
}
catch (IOException e) {
e.printStackTrace();
}
System.out.println(str);
以上是Action和调用Action的方法,因为是我写的一个小demo,所以没有真实的数据。
通过执行main方法返回了:
{ "ID": "123", "success": "true"} 这个就是我在Action里定义的返回数据了。
下面在把HTTP调用的方法代码贴出来:
public static String send(String urlString, String method,
String parameters)
throws IOException {
HttpURLConnection urlConnection = null;
URL url = new URL(urlString);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod(method);
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setUseCaches(false);
urlConnection.setRequestProperty("content-type", "text/html;charset=utf-8");
urlConnection.getOutputStream().write(parameters.getBytes("UTF-8"));
urlConnection.getOutputStream().flush();
urlConnection.getOutputStream().close();
//读取返回的流
InputStream input=urlConnection.getInputStream();
InputStreamReader inpurread=new InputStreamReader(input,"utf-8");
BufferedReader br=new BufferedReader(inpurread);
String a;
StringBuffer s=new StringBuffer();
while ((a=br.readLine())!=null) {
s.append(a);
}
return s.toString();
}
以上就是完整的通过HTTP的方式返回action了。通过这样的方式也可以实现webService的功能了。不过需要在Struts的配置文件里,把改action设置为不拦截,不然Action会拦截。