Example


-1. import Jersey类

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.multipart.FormDataMultiPart;
import com.sun.jersey.multipart.MultiPart;


-2. WebResource, ClientResponse, Client对象

private WebResource webRes;
private ClientResponse response;
private Client client = Client.create();


-3. Post multi part

/**
 * Jersey Post multipartentity
 */
public String executePostMultiPart(String requestUrl, String authorization) {  
    webRes = client.resource(requestUrl);
    MultiPart multipart = new FormDataMultiPart().field("property1", "value1")
            .field("property2", "value2").field("property3", "value3");
    response = webRes.accept(MediaType.APPLICATION_JSON).type(MediaType.MULTIPART_FORM_DATA_TYPE)
            .header(HttpHeaders.AUTHORIZATION, authorization)
            .post(ClientResponse.class, multipart);
    String output = response.getEntity(String.class);
    String statusCode=response.getStatus();
    return output;
}


-4. Post Json

/**
 * Jersey Post Json input
 */
public String executePost(String requestUrl, String input, String authorization) {
    webRes = client.resource(requestUrl);
    response = webRes.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON)
                .header(HttpHeaders.AUTHORIZATION, authorization)
                .post(ClientResponse.class, input);
    String output = response.getEntity(String.class);
    String statusCode=response.getStatus();
    return output; 
}


-5. Get

 /**
 * Jersey Get
 */
public String executeGet(String requestUrl, String authorization) {
    webRes = client.resource(requestUrl);
    response = webRes.type(MediaType.APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, authorization)
                .get(ClientResponse.class);
    String output = response.getEntity(String.class);
    String statusCode=response.getStatus();
    return output;
}


-6. 其他常用

/**
 * Jersey Put, delete, head ...etc
 */
webRes.put(ClientResponse.class, input);
webRes.delete(ClientResponse.class);
webRes.head()