Java 从servlet调用JAX-RS服务
我目前正在使用Eclipse开发一个java web应用程序。我创建了一个网页servlet,要求用户选择要上载的文件,我有一个web服务,我想处理该文件 我的问题是如何将参数从servlet传递到web服务,然后从servlet调用服务 我尝试过使用上下文和Httpconnections来实现这一点的方法,但两种方法似乎都没有效果 任何帮助或建议都将不胜感激 我的servlet代码:Java 从servlet调用JAX-RS服务,java,eclipse,web-services,servlets,Java,Eclipse,Web Services,Servlets,我目前正在使用Eclipse开发一个java web应用程序。我创建了一个网页servlet,要求用户选择要上载的文件,我有一个web服务,我想处理该文件 我的问题是如何将参数从servlet传递到web服务,然后从servlet调用服务 我尝试过使用上下文和Httpconnections来实现这一点的方法,但两种方法似乎都没有效果 任何帮助或建议都将不胜感激 我的servlet代码: protected void doPost(HttpServletRequest request,
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(false);
String uploadfile = request.getParameter("uploadfile");
String Username = (String)session.getAttribute("Loginname");
URL url = new URL ("http://localhost:9763/CWEngine_1.0.0/services/engine");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", MediaType.TEXT_PLAIN);
Map<String, String> uname = new HashMap<String, String>();
Map<String, String> ufile = new HashMap<String, String>();
String output = uname.put("loginname", Username) + ufile.put("ufile", uploadfile);
OutputStreamWriter os = new OutputStreamWriter(conn.getOutputStream());
os.write(output);
os.close();
}
受保护的void doPost(HttpServletRequest请求,
HttpServletResponse响应)引发ServletException,IOException{
HttpSession session=request.getSession(false);
字符串uploadfile=request.getParameter(“uploadfile”);
字符串用户名=(字符串)session.getAttribute(“Loginname”);
URL=新URL(“http://localhost:9763/CWEngine_1.0.0/services/engine");
HttpURLConnection conn=(HttpURLConnection)url.openConnection();
连接设置输出(真);
conn.setRequestMethod(“POST”);
conn.setRequestProperty(“内容类型”,MediaType.TEXT_-PLAIN);
Map uname=new HashMap();
Map ufile=新的HashMap();
字符串输出=uname.put(“loginname”,Username)+ufile.put(“ufile”,uploadfile);
OutputStreamWriter os=新的OutputStreamWriter(conn.getOutputStream());
写入(输出);
os.close();
}
我的web服务代码:
@Path("/")
public class Engine {
@Context
private static ServletContext context;
@POST
@Consumes(MediaType.TEXT_PLAIN)
public void main(String[] args) {
URL url = null;
HttpURLConnection connection = null;
try {
url = new URL ("http://localhost:9763/CWEngine_1.0.0/services/engine");
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
connection = (HttpURLConnection) url.openConnection();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
BufferedReader input = null;
try {
input = new BufferedReader(new InputStreamReader(connection.getInputStream()));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//String output = uname.put("loginname", Username) + ufile.put("ufile", uploadfile);
Map<String, String> uname = (Map<String, String>) ((ServletContext) input).getAttribute("uname");
String username = uname.get("loginname");
Map<String, String> ufile = (Map<String, String>) context.getAttribute("ufile");
String uploadfile = ufile.get("ufile");
System.out.println(uploadfile + username);
@Path(“/”)
公共级引擎{
@上下文
私有静态ServletContext;
@职位
@使用(MediaType.TEXT\u PLAIN)
公共void main(字符串[]参数){
URL=null;
HttpURLConnection=null;
试一试{
url=新url(“http://localhost:9763/CWEngine_1.0.0/services/engine");
}捕获(格式错误的异常e1){
//TODO自动生成的捕捉块
e1.printStackTrace();
}
试一试{
connection=(HttpURLConnection)url.openConnection();
}捕获(IOE1异常){
//TODO自动生成的捕捉块
e1.printStackTrace();
}
BufferedReader输入=null;
试一试{
输入=新的BufferedReader(新的InputStreamReader(connection.getInputStream());
}捕获(IOE1异常){
//TODO自动生成的捕捉块
e1.printStackTrace();
}
//字符串输出=uname.put(“loginname”,Username)+ufile.put(“ufile”,uploadfile);
Map uname=(Map)((ServletContext)输入).getAttribute(“uname”);
字符串username=uname.get(“loginname”);
Map ufile=(Map)context.getAttribute(“ufile”);
字符串uploadfile=ufile.get(“ufile”);
System.out.println(上传文件+用户名);
您可以在servlet中构建rs客户端
首先,您必须构建一个rs客户机
javax.ws.rs.client.Client client = ClientBuilder.newClient();
package com.blithe.client;
import java.util.List;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Invocation.Builder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.MediaType;
public class RSClient {
public static void main(String [] args){
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://localhost:8080/RestPOM/services/helloworld");
Builder builder = target.request(MediaType.APPLICATION_JSON);
List<String> list =builder.post(null , new GenericType<List<String>>(){});
System.out.println(list.get(0)+list.get(1));
// the out put will be helloworld
}
}
然后指向restful服务url
WebTarget target = client.target("your restful service url");
并指定您希望获取的数据类型,以xml为例
Builder builder = target.request(MediaType.APPLICATION_XML);
最后指定http方法,以get为例
Type returnObj = builder.get(Type);
一旦执行builder.get(Type),它将返回一个类型为“Type”的对象。“Type”必须与restful服务的返回类型相同
在您的情况下,您需要使用
builder.post(Entity.entity("your input Object", "the media type"));
我使用jersey最多,这里是官方网站,供您进一步参考客户端API。
我会给你一个简单的可运行的例子 我的pom依赖性
<dependencies>
<!-- jackson json dependency -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.6.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.6.5</version>
</dependency>
<!-- jersey dependency -->
<dependency>
<groupId>org.glassfish.jersey.bundles</groupId>
<artifactId>jaxrs-ri</artifactId>
<version>2.21.1</version>
</dependency>
<!-- make jersey auto marshel to json -->
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.21.1</version>
</dependency>
<!-- make jersey auto marshel to xml -->
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-jaxb</artifactId>
<version>2.21.1</version>
</dependency>
<dependency>
<groupId>org.codehaus.woodstox</groupId>
<artifactId>stax2-api</artifactId>
<version>3.1.4</version>
</dependency>
</dependencies>
简单的资源
package com.blithe.resource;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Path("helloworld")
public class HelloWorldResource
{
@POST
@Produces(MediaType.APPLICATION_JSON)
public List<String> getStringArray(){
List<String> list = new ArrayList<>();
list.add("hello");
list.add("world");
return list;
}
}
package com.blit.resource;
导入java.util.ArrayList;
导入java.util.List;
导入javax.ws.rs.POST;
导入javax.ws.rs.Path;
导入javax.ws.rs.products;
导入javax.ws.rs.core.MediaType;
@路径(“helloworld”)
公共类HelloWorldResource
{
@职位
@产生(MediaType.APPLICATION_JSON)
公共列表getStringArray(){
列表=新的ArrayList();
添加(“你好”);
列表。添加(“世界”);
退货清单;
}
}
还有一个rs客户端
javax.ws.rs.client.Client client = ClientBuilder.newClient();
package com.blithe.client;
import java.util.List;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Invocation.Builder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.MediaType;
public class RSClient {
public static void main(String [] args){
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://localhost:8080/RestPOM/services/helloworld");
Builder builder = target.request(MediaType.APPLICATION_JSON);
List<String> list =builder.post(null , new GenericType<List<String>>(){});
System.out.println(list.get(0)+list.get(1));
// the out put will be helloworld
}
}
package com.blit.client;
导入java.util.List;
导入javax.ws.rs.client.client;
导入javax.ws.rs.client.ClientBuilder;
导入javax.ws.rs.client.Invocation.Builder;
导入javax.ws.rs.client.WebTarget;
导入javax.ws.rs.core.GenericType;
导入javax.ws.rs.core.MediaType;
公共类RSClient{
公共静态void main(字符串[]args){
Client Client=ClientBuilder.newClient();
WebTarget=client.target(“http://localhost:8080/RestPOM/services/helloworld");
Builder=target.request(MediaType.APPLICATION\ujson);
List List=builder.post(null,新的GenericType(){});
System.out.println(list.get(0)+list.get(1));
//被驱逐的将是地狱世界
}
}
在服务器上运行项目以发布restful服务,然后运行main()方法。您应该可以在控制台上看到helloworld
您需要做的是,在servlet中创建一个rs客户端。您可以参考上面的RSClient。谢谢您的回复!您能否建议我如何从web服务中检索帖子信息?如果将“Type returnobj=builder.get(Type);”行放在服务中,是否可以这样做?