有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

安卓/java在项目中组织http web服务调用的结构/模式是什么?

现在只要我的项目在后端有一个web服务。我习惯于用这种结构/模式创建我的项目

项目

  • HttpMethods包
    • HttpGetThread
    • HttpPostThread
    • HttpMultipartPostThread
  • 接口包
    • iPod响应

我在这些JAVA文件中编写的代码是

ipostreponse。爪哇

public interface IPostResponse {
    public void getResponse(String response);
}

HttpGetThread。爪哇

public class HttpGetThread extends Thread {

    private String url;
    private final int HTTP_OK = 200;
    private IPostResponse ipostObj;

    public HttpGetThread(String url, IPostResponse ipostObj) {
        this.url = url;
        this.ipostObj = ipostObj;
    }

    public void run() {
        try {
            HttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);
            HttpResponse httpResponse = httpClient.execute(httpGet);
            int responseCode = httpResponse.getStatusLine().getStatusCode();
            if (responseCode == HTTP_OK) {
                InputStream inputStream = httpResponse.getEntity().getContent();
                int bufferCount = 0;
                StringBuffer buffer = new StringBuffer();
                while ((bufferCount = inputStream.read()) != -1) {
                    buffer.append((char) bufferCount);
                }
                ipostObj.getResponse(buffer.toString());
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

HttpPostHttpMultipartPost类中,通过扩展Thread并具有一个构造函数和一个run方法,实现了相同的方法

那么

我实现了一个活动的接口,并将该主活动扩展到所有其他活动,并通过创建带有参数的Http类对象和call obj.start();来获取响应和调用


我仍然相信:我缺少很多东西,或者这个结构很差

我需要知道,对于一个Android应用程序来说,要在几乎所有的活动中实现Web服务调用并具有代码可重用性,我应该遵循哪种模式/结构

我刚刚看到Facebook如何进行web服务调用,例如登录/注销,它有登录和注销侦听器

是否有相关的博客/文章/答案?请问,任何用户能否分享他/她的优秀经验和解决方案

我更感兴趣的是“我的类和接口应该是什么样子,应该有什么样的方法?”


共 (2) 个答案

  1. # 1 楼答案

    我知道这是一个老生常谈的问题,但我仍然想回答这个问题,分享我在自己的项目中所做的事情,我会喜欢社区对我的方法的建议

    HttpClient

    如果你看一下HttpClient(作为向端点发出请求的实体),它完全是关于请求和响应的。这样想吧。Http协议“发送请求”的行为需要方法、头(可选)、体(可选)。同样,作为对请求的回应,我们会得到带有状态码、标题和正文的响应。因此,您只需将您的HttpClient设置为:

    public class HttpClient 
    {
        ExecutorService executor = Executors.newFixedThreadPool(5);
         //method below is just prototype 
         public String execute(String method, String url, Map < String, String > headers ) 
         {
              try 
              {
               URL url = new URL("http://www.javatpoint.com/java-tutorial");
               HttpURLConnection huc = (HttpURLConnection) url.openConnection();
               //code to write headers, body if any
               huc.disconnect();
               //return data
              } 
              catch (Exception e) 
              {
               System.out.println(e);
              }
         }
    
           public String executeAsync(String method, String url, Map < String, String > headers, Callback callback ) 
         {//Callback is Interface having onResult()
             executor.execute(
                 new Runnable()
                 {
                     void run()
                     {
                        String json= execute(method,url,headers)
                        callback.onResult(json);
                     }
                 }
              );
         }
    }
    

    这样,就不需要为单独的请求创建类。相反,我们将只使用HtttpClient。您必须在其他线程(而不是Android的主线程)上调用API

    API结构

    假设你有一个名为User的资源,你的应用程序中需要CRUD。您可以创建接口UserRepository和实现UserRepositoryImpl

    interface UserRepository
    {
        void get(int userId, Callback callback);
    
        void add(String json,Callback callback);
    
        //other methods
    }
    
    
    class UserRepositoryImp
    {
        void get(int userId, Callback callback)
        {
            HttpClient httpClient= new HttpClient();
            //create headers map
            httpClient.executeAsync("GET","/",authHeaders,callback);
        }
    
        void add(String json,Callback callback)
        {
             HttpClient httpClient= new HttpClient();
            //create headers map
            httpClient.executeAsync("POST","/",authHeaders,callback);
        }
    
        //other methods
    }
    

    请注意,您应该在Android的UI线程上更新UI。[上面的实现并不担心这一点]

  2. # 2 楼答案

    第一个也是最重要的建议是,为什么不使用Painless ThreadingAsyncTask

    现在,第二件事是创建一个可重用的代码,如下所示,您可以使用请求参数创建尽可能多的方法

    public class JSONUtil {
    
        private static JSONUtil inst;
    
        private JSONUtil() {
    
        }
    
        public static JSONUtil getInstance() {
            if (inst == null)
                inst = new JSONUtil();
            return inst;
        }
    
        /**
         * Request JSON based web service to get response
         * 
         * @param url
         *            - base URL
         * @param request
         *            - JSON request
         * @return response
         * @throws ClientProtocolException
         * @throws IOException
         * @throws IllegalStateException
         * @throws JSONException
         */
        public HttpResponse request(String url, JSONObject request)
                throws ClientProtocolException, IOException, IllegalStateException,
                JSONException {
    
            synchronized (inst) {
    
                DefaultHttpClient client = new DefaultHttpClient();
                HttpPost post = new HttpPost(url);
                post.setEntity(new StringEntity(request.toString(), "utf-8"));
                HttpResponse response = client.execute(post);
                return response;
            }
        }
    
        public HttpResponse request(String url)
                throws ClientProtocolException, IOException, IllegalStateException,
                JSONException {
    
            synchronized (inst) {
    
                DefaultHttpClient client = new DefaultHttpClient();             
                HttpPost post = new HttpPost(url);
                post.addHeader("Cache-Control", "no-cache");
                HttpResponse response = client.execute(post);
                return response;
            }
        }
    }