I'm trying to get data from a JSON request in Apache Struts 2.
I've tested with this url: http://date.jsontest.com/.
In StrutsJsonClientAction.java
file, line
System.out.println(result);
prints this to the console:
{ "time": "12:04:12 PM", "milliseconds_since_epoch": 1431086652240, "date": "05-08-2015"}
I want to know how to show this result in result.jsp
Today, I found there is resttemplate can use in spring,I want to know are there the tools like restemplate in struts2 that I can use??
My current solution: StrutsJsonClientAction.java
package com.example.action;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
public class StrutsJsonClientAction extends ActionSupport{
private static final long serialVersionUID = 1L;
private final String url="http://date.jsontest.com/";
public String execute() throws Exception {
HttpServletRequest request= ServletActionContext.getRequest();
request.setCharacterEncoding("utf-8");
URL myUrl = new URL(url);
//System.out.println(myUrl.toString());
HttpURLConnection connection = (HttpURLConnection) myUrl.openConnection();
connection.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"utf-8"));
String result="";
String temp=null;
while ((temp=reader.readLine())!= null) {
result=result+temp;
}
System.out.println(result);
return SUCCESS;
}
}
file struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<package name="struts2" extends="struts-default">
<action name="GoToGetApi" class="com.example.action.StrutsJsonClientAction">
<result>/resault.jsp</result>
</action>
</package>
</struts>