问题
I have been creating a Rest client using jersey.
I am getting the following exception:
com.sun.jersey.api.client.ClientHandlerException: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at com.sun.jersey.client.urlconnection.URLConnectionClientHandler.handle(URLConnectionClientHandler.java:128)
at com.sun.jersey.api.client.Client.handle(Client.java:435)
at com.sun.jersey.api.client.WebResource.handle(WebResource.java:557)
at com.sun.jersey.api.client.WebResource.access$300(WebResource.java:69)
at com.sun.jersey.api.client.WebResource$Builder.put(WebResource.java:475)
Below is my rest client:
public class RestClient {
private WebResource webResource;
private Client client;
private static String BASE_URI;
public RestClient(String url)
{
BASE_URI = url;
}
private void connect() {
com.sun.jersey.api.client.config.ClientConfig config = new com.sun.jersey.api.client.config.DefaultClientConfig();
client = Client.create(config);
client.setReadTimeout(50000);
webResource = client.resource(BASE_URI);
}
private void disconnect() {
client.destroy();
}
public TResponse topup(TRequest request) {
TResponse respone=null;
try{
System.out.println("::::::::::::::::start");
this.connect();
System.out.println("connected to base URL "+BASE_URI);
ClientResponse clientRequest = webResource.path("/topup").accept(MediaType.APPLICATION_XML).put(ClientResponse.class, request);
respone = (TopUpResponse)clientRequest.getEntity(TopUpResponse.class);
this.disconnect();
}
catch(Exception e){
e.printStackTrace();
}
System.out.println(":::::::::finish");
return respone;
}
}
Please help me to sort out this exception. Thanks in advance.
回答1:
Do you have @XxmlRootElement annotation. Please read this article for more details
回答2:
With jersey api all seems easy:
GET call.
Client client = Client.create();
WebResource webResource = client.resource("http://sample.com/rest_service");
MultivaluedMap queryParams = new MultivaluedMapImpl();
queryParams.add("PARAM1", param1);
queryParams.add("PARAM2", param2);
RESTResult s = webResource.queryParams(queryParams)
//Check the return type of the service
.accept(MediaType.APPLICATION_JSON)
//Put a object with XmlRootElement to map the result
.get(RESTResult .class);
println(s.status);
//Also you can return the result in a string
String s = webResource.queryParams(queryParams).get(String.class);
RESTResult code
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class RESTAuthorizationResult
{
public String status = "";
public String message = "";
}
来源:https://stackoverflow.com/questions/12312421/error-on-creating-rest-client-using-jersey