我首先创建了一个带有@GET方法的基本Web服务,如下所示。
package com.webservice.eoin;
import java.awt.PageAttributes.MediaType;
import java.util.ArrayList;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
@Path("/webservice")
public class Web_service {
@PUT
@Path("/getname")
@Produces("text/plain")
public String getname()
{
return "hello!!!";
}
}
当我运行它时,这工作正常。我有所有jar文件和web.xml文件设置等。我接下来要做的是创建一个客户端,它将字符串的arraylist发送到webservice并将修改后的arraylist版本返回给客户端。我的问题首先是你如何建立客户?以及如何运行它以便将此arraylist发送到服务器。我已经阅读了很多教程,但我发现其中一些难以理解。我是用Java制作webservices的新手。提前谢谢
答案 0 :(得分:2)
首先,我很抱歉我从我目前正在处理的项目中复制了很多代码,但是否则会很麻烦。如果我有拼写错误或编译错误,请原谅。另外,请注意您需要一个外部库。
客户:
import java.net.URI;
import java.util.List;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;
import com.sun.jersey.api.client.GenericType;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.client.apache.ApacheHttpClient;
import com.sun.jersey.client.apache.config.ApacheHttpClientConfig;
import com.sun.jersey.client.apache.config.DefaultApacheHttpClientConfig;
public Client {
private final URI fServerURI;
private final ApacheHttpClient fClient;
private final MediaType fMediaType= MediaType.APPLICATION_XML_TYPE;
public Client() {
final String apiEndpoint= "...";
final DefaultApacheHttpClientConfig clientConfig;
fServerURI= UriBuilder.fromUri(apiEndpoint).build();
clientConfig= new DefaultApacheHttpClientConfig();
clientConfig.getProperties().put(ApacheHttpClientConfig.PROPERTY_HANDLE_COOKIES, true);
fClient= ApacheHttpClient.create(clientConfig);
}
private <T> T call(WebResource resource, RequestType requestType, Object requestEntity, GenericType<T> acceptType, String taskMessage) {
return acceptCall(resource, requestType, acceptType, requestEntity);
}
private <T> T acceptCall(WebResource resource, RequestType requestType, GenericType<T> acceptType, Object requestEntity) {
switch (requestType) {
case POST:
return resource.accept(fMediaType).post(acceptType, requestEntity);
case PUT:
return resource.accept(fMediaType).put(acceptType, requestEntity);
case DELETE:
resource.accept(fMediaType).delete();
return null;
default:
return resource.accept(fMediaType).get(acceptType);
}
public MyArrayList sendArrayList(MyArrayList list) {
WebResource resource= createResource();
resource= resource.path("webservice").path("sendarraylist");
resource= resource.queryParam("arraylist", list);
return call(resource, RequestType.POST, null, new GenericType<MyArrayList>() {
}, "Send my array list");
}
public static void main(String ... args) {
Client c= new Client();
MyArrayList result= c.sendArrayList(new MyArrayList(/*whatevs goes inside*/));
}
}
在服务器中,您需要以下内容:
@POST
@Path("/sendarraylist")
@Consumes(MediaType.APPLICATION_XML)
@Produces(MediaType.APPLICATION_XML)
MyArrayList modifyList(@QueryParam("arraylist") MyArrayList list) {
//do stuff
}
剩下的最后一件事是根据JAXB规则创建MyArrayList
类(参见此示例:http://www.vogella.com/articles/JAXB/article.html)