Java 如何使用volley库访问restful web服务方法
我已经使用本教程创建了一个restful web服务,在运行本教程之后,我得到了一个自动生成的java文件,其中包含以下代码Java 如何使用volley库访问restful web服务方法,java,android,rest,android-volley,Java,Android,Rest,Android Volley,我已经使用本教程创建了一个restful web服务,在运行本教程之后,我得到了一个自动生成的java文件,其中包含以下代码 public class RestAPI { private final String urlString = "http://125.0.0.174/Handler1.ashx"; private static String convertStreamToUTF8String(InputStream stream) throws IOExceptio
public class RestAPI {
private final String urlString = "http://125.0.0.174/Handler1.ashx";
private static String convertStreamToUTF8String(InputStream stream) throws IOException {
String result = "";
StringBuilder sb = new StringBuilder();
try {
InputStreamReader reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[4096];
int readedChars = 0;
while (readedChars != -1) {
readedChars = reader.read(buffer);
if (readedChars > 0)
sb.append(buffer, 0, readedChars);
}
result = sb.toString();
} catch (UnsupportedEncodingException e){
e.printStackTrace();
}
return result;
}
private String load(String contents) throws IOException {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(60000);
Log.e("load r2","load r2");
conn.setDoOutput(true);
conn.setDoInput(true);
OutputStreamWriter w = new OutputStreamWriter(conn.getOutputStream());
w.write(contents);
w.flush();
InputStream istream = conn.getInputStream();
String result = convertStreamToUTF8String(istream);
return result;
}
private Object mapObject(Object o) {
Object finalValue = null;
if (o.getClass() == String.class) {
finalValue = o;
}
else if (Number.class.isInstance(o)) {
finalValue = String.valueOf(o);
} else if (Date.class.isInstance(o)) {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss", new Locale("en", "USA"));
finalValue = sdf.format((Date)o);
}
else if (Collection.class.isInstance(o)) {
Collection<?> col = (Collection<?>) o;
JSONArray jarray = new JSONArray();
for (Object item : col) {
jarray.put(mapObject(item));
}
finalValue = jarray;
} else {
Map<String, Object> map = new HashMap<String, Object>();
Method[] methods = o.getClass().getMethods();
for (Method method : methods) {
if (method.getDeclaringClass() == o.getClass()
&& method.getModifiers() == Modifier.PUBLIC
&& method.getName().startsWith("get")) {
String key = method.getName().substring(3);
try {
Object obj = method.invoke(o, null);
Object value = mapObject(obj);
map.put(key, value);
finalValue = new JSONObject(map);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
return finalValue;
}
public JSONObject GetDoctors(String Terr_Code) throws Exception {
JSONObject result = null;
JSONObject o = new JSONObject();
JSONObject p = new JSONObject();
o.put("interface","RestAPI");
o.put("method", "GetDoctors");
p.put("Terr_Code",mapObject(Terr_Code));
o.put("parameters", p);
String s = o.toString();
String r = load(s);
result = new JSONObject(r);
return result;
}
public JSONObject GetUserDetail(String IMEINO) throws Exception {
JSONObject result = null;
JSONObject o = new JSONObject();
JSONObject p = new JSONObject();
o.put("interface","RestAPI");
o.put("method", "GetUserDetail");
p.put("IMEINO",mapObject(IMEINO));
o.put("parameters", p);
String s = o.toString();
String r = load(s);
result = new JSONObject(r);
return result;
}
}
公共类RestAPI{
私有最终字符串urlString=”http://125.0.0.174/Handler1.ashx";
私有静态字符串convertStreamToUTF8String(InputStream流)引发IOException{
字符串结果=”;
StringBuilder sb=新的StringBuilder();
试一试{
InputStreamReader reader=新的InputStreamReader(流,“UTF-8”);
char[]buffer=新字符[4096];
int readedChars=0;
while(readedChars!=-1){
readedChars=reader.read(缓冲区);
如果(读取字符>0)
sb.追加(缓冲区,0,readedChars);
}
结果=sb.toString();
}捕获(不支持的编码异常e){
e、 printStackTrace();
}
返回结果;
}
私有字符串加载(字符串内容)引发IOException{
URL=新URL(URL字符串);
HttpURLConnection conn=(HttpURLConnection)url.openConnection();
conn.setRequestMethod(“POST”);
连接设置连接超时(60000);
Log.e(“负载r2”,“负载r2”);
连接设置输出(真);
conn.setDoInput(真);
OutputStreamWriter w=新的OutputStreamWriter(conn.getOutputStream());
w、 写(内容);
w、 冲洗();
InputStream istream=conn.getInputStream();
字符串结果=convertStreamToUTF8String(istream);
返回结果;
}
私有对象映射对象(对象o){
对象finalValue=null;
if(o.getClass()==String.class){
最终价值=o;
}
else if(编号、类别、实例(o)){
finalValue=String.valueOf(o);
}else if(日期、类别、持续时间(o)){
SimpleDateFormat sdf=新SimpleDateFormat(“MM/dd/yyyy hh:MM:ss”,新语言环境(“en”,“USA”);
最终值=sdf.格式((日期)o);
}
else if(Collection.class.isInstance(o)){
集合col=(集合)o;
JSONArray jarray=新的JSONArray();
用于(对象项:col){
jarray.put(映射对象(项));
}
最终价值=jarray;
}否则{
Map Map=newhashmap();
方法[]方法=o.getClass().getMethods();
用于(方法:方法){
if(method.getDeclaringClass()==o.getClass()
&&方法.getModifiers()==Modifier.PUBLIC
&&方法.getName().startsWith(“get”)){
String key=method.getName().substring(3);
试一试{
Object obj=method.invoke(o,null);
对象值=映射对象(obj);
map.put(键、值);
最终值=新的JSONObject(映射);
}捕获(例外e){
e、 printStackTrace();
}
}
}
}
返回最终值;
}
公共JSONObject GetDoctors(字符串Terr_代码)引发异常{
JSONObject结果=null;
JSONObject o=新的JSONObject();
JSONObject p=新的JSONObject();
o、 put(“接口”、“重新启动PI”);
o、 put(“方法”、“获取医生”);
p、 put(“地球代码”,地图对象(地球代码));
o、 put(“参数”,p);
字符串s=o.toString();
字符串r=荷载;
结果=新的JSONObject(r);
返回结果;
}
公共JSONObject GetUserDetail(字符串IMEINO)引发异常{
JSONObject结果=null;
JSONObject o=新的JSONObject();
JSONObject p=新的JSONObject();
o、 put(“接口”、“重新启动PI”);
o、 put(“方法”、“GetUserDetail”);
p、 put(“IMEINO”,映射对象(IMEINO));
o、 put(“参数”,p);
字符串s=o.toString();
字符串r=荷载;
结果=新的JSONObject(r);
返回结果;
}
}
我在async任务中调用这个类,一切都很好,但我想通过截击使用它,因为async任务很慢。
这个类只有一个url,我不知道如何为单个方法调用这个url,我尝试了下面的代码,但得到了错误的url异常。请告诉我如何使用单独的URL访问RESTAPI的方法
public void requestJSON() {
String tag_json_obj = "json_obj_req";
final ProgressDialog pDialog = new ProgressDialog(context);
pDialog.setMessage("Loading...");
pDialog.show();
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET, null,
null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
RestAPI restAPI = new RestAPI();
response = restAPI.GetDoctors(terrcode);
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
display.setText(response.toString());
pDialog.hide();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
display.setText(error.toString());
pDialog.hide();
}
});
// Adding request to request queue
VolleySingleton.getInstance().addToRequestQueue(jsonObjReq,
tag_json_obj);
}
public void requestJSON(){
字符串tag_json_obj=“json_obj_req”;
final ProgressDialog pDialog=新建ProgressDialog(上下文);
设置消息(“加载…”);
pDialog.show();
JsonObjectRequest JSONObjectReq=新的JsonObjectRequest(Method.GET,null,
null,新响应。侦听器(){
@凌驾
公共void onResponse(JSONObject响应){
试一试{
RestAPI RestAPI=新RestAPI();
响应=restAPI.GetDoctors(terrcode);
}
捕获(例外e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
display.setText(response.toString());
pDialog.hide();
}
},new Response.ErrorListener(){
@凌驾
公共无效onErrorResponse(截击错误){
display.setText(error.toString());
pDialog.hide();
}
});
//将请求添加到请求队列
VolleySingleton.getInstance().addToRequestQueue(jsonObjReq,
标签(json)(obj);;
}
使用截击作为截击服务:
public class VolleyService {
private static VolleyService instance;
private RequestQueue requestQueue;
private ImageLoader imageLoader;
private VolleyService(Context context) {
requestQueue = Volley.newRequestQueue(context);
imageLoader = new ImageLoader(requestQueue, new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap> cache = new LruCache<String, Bitmap>(20);
@Override
public Bitmap getBitmap(String url) {
return cache.get(url);
}
@Override
public void putBitmap(String url, Bitmap bitmap) {
cache.put(url,bitmap);
}
});
}
public static VolleyService getInstance(Context context) {
if (instance == null) {
synchronized(VolleyService.class) {
if (instance == null) {
instance = new VolleyService(context);
}
}
}
return instance;
}
public RequestQueue getRequestQueue() {
return requestQueue;
}
public ImageLoader getImageLoader() {
return imageLoader;
}
}
公共类截击服务{
私有静态截击服务实例;
私有请求队列请求队列;
私有图像加载器;
专用截击服务(上下文){
requestQueue=Volley.newRequestQueue(上下文);
imageLoader=new imageLoader(requestQueue,new imageLoader.ImageCache(){
专用最终LruCache缓存=新LruCache(20);
@凌驾
公共图书馆
RequestQueue queue = VolleyService.getInstance(this.getContext()).getRequestQueue();
StringRequest request = new StringRequest(url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// we got the response, now our job is to handle it
try {
//Here you parse your JSON - best approach is to use GSON for deserialization
getJsonFromResponse(response);
} catch (RemoteException | OperationApplicationException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//something happened, treat the error.
Log.e("Error", error.toString());
}
});
queue.add(request);