天天看點

java 通過HTTP的方式調用Action

用SSH架構寫了一個微信項目,因為要和别的項目對接接口,本來想用WebService來實作,後來看到别的架構裡面直接通過Actio來實作對接,是以就想到了用Action作為接口來實作WebService功能,通過HTTP來調用。代碼如下。

Action代碼:

public String testService() throws IOException, ClassNotFoundException{

//建立request和response對象

HttpServletResponse 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用于轉換

//參數

map.put("ID", "123123");

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會攔截。