Java程序访问服务器(使用Jersey开发RESTful的webservice服务器)的方法:
String url = "http://.../hotel_robot/ws/restful/...";
ClientConfig cc = new DefaultClientConfig();
Client c = Client.create(cc);
MultivaluedMap<String, String> params = new MultivaluedMapImpl();
params.add("a","0");
params.add("b","0");
WebResource wr = c.resource(url);
String response = wr.post(String.class, params);
System.out.println("result:"+response);
Android客户端访问服务器(使用Jersey开发RESTful的webservice服务器)的方法(当然在线程里):
//只修改此处一行:ClientResponse response = wr.queryParams(params).post(ClientResponse.class); 如果用上面Java的写法会报如下错误:
//A message body writer for Java type, class com.sun.jersey.core.util.MultivaluedMapImpl, and MIME media type, application/octet-stream, was not found
//相较于Java要注意三个地方,不然会报错:1、返回类型ClientResponse 2、参数params的传递
//3、不能分两步写,会报错wr.queryParams(params); wr.queryParams(params).post(ClientResponse.class);
String url = "http://.../hotel_robot/ws/restful/...";
ClientConfig cc = new DefaultClientConfig();
Client c = Client.create(cc);
MultivaluedMap<String, String> params = new MultivaluedMapImpl();
params.add("a","0");
params.add("b","0");
WebResource wr = c.resource(url);
ClientResponse response = wr.queryParams(params).post(ClientResponse.class);
InputStream in = response.getEntityInputStream();
System.out.println("result:");//服务器返回结果只能通过流InputStream读取出来
同时导Jersey包时注意可能因为client、core、json三个包的版本不同导致编译问题,需要在app的build.gradle里的android里添加:
android {
packagingOptions {
exclude 'META-INF/DEPENDENCIES'
exclude 'META-INF/LICENSE'
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/license.txt'
exclude 'META-INF/NOTICE'
exclude 'META-INF/NOTICE.txt'
exclude 'META-INF/notice.txt'
exclude 'META-INF/ASL2.0'
exclude 'META-INF/jersey-module-version'
exclude 'META-INF/services/javax.ws.rs.ext.MessageBodyWriter'
exclude 'META-INF/services/javax.ws.rs.ext.MessageBodyReader'
}
}
这里困扰了我2天,特记笔记。