java使用Jersey调用rest api实例
Jersey的各个版本使用方法都不一样,而且网上对Client的解释也不多。折腾了一天,终于搞定了。
我用的版本是1.19,需要以下几个jar包:
首先要写一个网络访问类,这里举了post和delete的例子,其他的方法基本相同:
我用的版本是1.19,需要以下几个jar包:
首先要写一个网络访问类,这里举了post和delete的例子,其他的方法基本相同:
import java.util.HashMap;使用的例子(创建群组方法,注意这里面使用了设置参数和Header的方法):
import java.util.Map;
import java.util.Set;
import com.google.gson.Gson;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.WebResource.Builder;
public class HXRequest {
private String url;
private Map<String, Object> param = new HashMap<String, Object>();
private Map<String, String> header = new HashMap<String, String>();
public HXRequest(String url){
this.url = url;
}
public void setParam(String key, Object value) {
param.put(key, value);
}
public void setHeader(String key, String value) {
header.put(key, value);
}
/**
* 向指定URL发送POST方法的请求
*/
public String sendPost() {
Client client = Client.create();
WebResource resource = client.resource(url);
Builder builder = resource.header("Content-Type", "application/json");
Set<String> keys = header.keySet();
if(keys != null && keys.size() > 0){
for (String key : keys) {
builder = builder.header(key, header.get(key));
}
}
try {
String result = builder.entity(new Gson().toJson(param)).post(String.class);
System.out.println(result);
return result;
} catch(Exception e){
e.printStackTrace();
return null;
}
}
/**
* 向指定URL发送DELETE方法的请求
*/
public String sendDelete() {
Client client = Client.create();
WebResource resource = client.resource(url);
Builder builder = resource.header("Content-Type", "application/json");
Set<String> keys = header.keySet();
if(keys != null && keys.size() > 0){
for (String key : keys) {
builder = builder.header(key, header.get(key));
}
}
try {
String result = builder.entity(new Gson().toJson(param)).delete(String.class);
System.out.println(result);
return result;
} catch(Exception e){
e.printStackTrace();
return null;
}
}
}
/**
* 创建群组
* @param hxname
* @return
*/
public static HXResult<HXGroup> createGroup(String hxname, String groupName, String token){
HXRequest request = new HXRequest(createGroupUrl);
request.setParam("groupname", groupName);
request.setParam("desc", groupName);
request.setParam("public", true);
request.setParam("approval", false);
request.setParam("owner", hxname);
request.setHeader("Authorization", "Bearer " + token);
String result = request.sendPost();
if(result == null)
return null;
HXResult<HXGroup> group = new Gson().fromJson(result,
new TypeToken<HXResult<HXGroup>>(){}.getType());
return group;
}